Вопрос

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?

Это было полезно?

Решение

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}'" 
}

Другие советы

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}'" }

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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top