[Rails] Re: Noob - Associated Tables Find Query

Chris Hall
Thu, 12 Jan 2006 17:31:53 -0000

class Match < ActiveRecord::Base
  has_many :predictions
end

class Prediction < ActiveRecord::Base
  belongs_to :match
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :predictions, :include => :matches
end

user = User.find(1)
cutoff_date = TIme.now.at_midnight

# all in code
predictions = user.predictions.collect { |p| p.match.match_date <cutoff_date
}

# db method
predictions = user.predictions.find(:all, :joins => "matches",
:conditions
=> ["predictions.match_id = match.id and match.match_date <= ?",
cutoff_date])

note, these are untested examples and there are pros/cons to using one over
the other.

Chris

On 1/12/06, Peter Baldwin <pucbaldwin@yahoo.co.uk>
wrote:
>
> Anyone able to help with this? Assistance would be much appreciated.
> Pete
>
>
> > I''m trying to write a football prediction game.
> >
> > I have a Matches table and a Predictions table.
> > Each Match :has_many Predictions, and each Prediction :belongs_to a
> > Match
> >
> > Each Match has (amongst other things) a Match.match_date field.
> > Each Prediction has (amongst other things) a User_id field
> >
> > I''m trying to get a list of all Predictions a particular User
has made
> > which "belong to" Matches for an arbitrary time period (e.g.
"Time.now
> > <= now()")
> > e.g. All "User 1"''s predictions relating to matches
from last week.
> >
> > Given that the tables are associated, is it possible to do a single
> > .find query stipulating both the Prediction.User_id and the
> > Match.match_date, which returns a list of a user''s
predictions for the
> > period?
>
>
>
> --
> Posted via http://www.ruby-forum.com/.
> _______________________________________________
> Rails mailing list
> Rails@lists.rubyonrails.org
> http://lists.rubyonrails.org/mailman/listinfo/rails
>
-------------- next part --------------
An HTML attachment was scrubbed...