views:

19

answers:

1

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::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!

+1  A: 

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.

tadman
Is it possible to just use that query but by doing `Outing.find_by_sql()` ?
amr
Just as a note, outings have many crews, so there's an outing_id in the crews table.
amr
ActiveRecord sometimes pretends it knows what you're talking about when you define relationships, but when you actually exercise them it falls flat on its face. If you've got a three level join that'll probably do it. `find_by_sql` could be what you need, too, if you can tweak the query enough.
tadman