I have an outings table, which basically holds some information about an 'outing'. These outings then have crews, which have users (through crew_users)
Just as a note, outings have many crews, so there's an outing_id in the crews table
Now, I need to find the user's next outing, as in the first outing where outing.start_time > Time.now
I've got this in my user.rb model:
has_many :crew_users
has_many :crews, :through => :crew_users
has_many :outings, :through => :crews
And when I try to do this:
>> Users.find(1).outings
I get this error:
ActiveRecord开发者_如何学JAVA::StatementInvalid: Mysql::Error: Unknown column 'crews.user_id'
in 'where clause': SELECT `outings`.* FROM `outings` INNER JOIN `crews` ON
`outings`.id = `crews`.outing_id WHERE ((`crews`.user_id = 1))
Anyone any ideas? Like I said, my goal is to get the user's next outing from the current time so there may very well be a much better to go about this!
You can try and reverse this is if doing a double :through
is out of the question by filtering the Outing records instead. The SQL for this would look something like:
SELECT outings.id FROM outings
LEFT JOIN crews ON crews.id=outings.crew_id
LEFT JOIN crews_users ON crews_users.crew_id=crews.id
WHERE crews_users.user_id=? AND start_time>=NOW()
ORDER BY created_at
LIMIT 1
The quick and dirty approach is to run this and extract the outing_id value you need, then call Outing.find
with that.
精彩评论