has_many conditions or proc on foreign key

2019-07-05 11:47发布

I have a has_many association between two models using a date as both the foreign and primary key for each model.

It works perfectly one way but not the other.

Works

has_one :quiz_log, :primary_key => :start_at, :foreign_key => :start_at

Doesn't work

has_many :event_logs, :primary_key => :start_at, :foreign_key => :start_at 

The reason being (i think) because the start_at on QuizLog is a date and the start_at on EventLog is a datetime. So it returns nil trying to match the exact datetime on a simple date.

How can I cast the foreign_key start_at on the second statement to convert it first from datetime to simply date so it will match the second model?

3条回答
做个烂人
2楼-- · 2019-07-05 12:24

After reading the title twice, I understand what you are asking for. May be something like the following would work?:

has_many :event_logs, :primary_key => :start_at, :conditions => proc { "start_date = '#{event_logs.start_date.to_date}'" }
查看更多
Rolldiameter
3楼-- · 2019-07-05 12:26

I'm not sure but I would use something like:

def event_logs
  EventLogs.where('event_logs.start_at >= ? AND event_logs.start_at < ?', start_at, start_at + 1.day)
end
查看更多
狗以群分
4楼-- · 2019-07-05 12:37

I'm not sure if you can do it without using finder_SQL, but this should work.

has_many :event_logs, :finder_sql => proc { 
   "SELECT * FROM event_logs WHERE DATE(event_logs.start_at) = '#{start_at}'" 
}
查看更多
登录 后发表回答