I have these models:
User -> Order -> Registration <- Camp
So a user has many orders, orders have many registrations and camps have
many registrations.
I have all the associations written up correctly, but I want to know how
to get all the users for a particular camp.
i.e.
@camp = Camp.find_by_name(“band camp”)
mycampers = @camp.orders.registrations.users
naturally, this doesn’t work – do i have to use sql here? the :include
option to find looks good, but I can’t get it to work.
best,
tim
Tim B. wrote:
i.e.
@camp = Camp.find_by_name(“band camp”)
mycampers = @camp.orders.registrations.users
naturally, this doesn’t work – do i have to use sql here? the :include
option to find looks good, but I can’t get it to work.
Something like
User.find :all, :select => ‘distinct users.*’,
:joins => {:orders => {:registrations => :camp}},
:conditions => [‘camps.name = ?’, camp_name]
–
We develop, watch us RoR, in numbers too big to ignore.
Tim B. wrote:
User -> Order -> Registration <- Camp
So a user has many orders, orders have many registrations and camps have
many registrations.
I have all the associations written up correctly, but I want to know how
to get all the users for a particular camp.
class Camp < ActiveRecord::Base
has_many :registrations
has_many :orders, :through => :registrations, :uniq => true, :include
=> :user
:
@camp = Camp.find_by_name(“band camp”)
mycampers = @camp.orders.map {|o| o.user}.uniq
Mark B. wrote:
Tim B. wrote:
User -> Order -> Registration <- Camp
So a user has many orders, orders have many registrations and camps have
many registrations.
I have all the associations written up correctly, but I want to know how
to get all the users for a particular camp.
class Camp < ActiveRecord::Base
has_many :registrations
has_many :orders, :through => :registrations, :uniq => true, :include
=> :user
:
@camp = Camp.find_by_name(“band camp”)
mycampers = @camp.orders.map {|o| o.user}.uniq
this is great! thanks for your help. is :uniq a custom method of
has_many :through ?
best,
tim
Tim B. wrote:
this is great! thanks for your help. is :uniq a custom method of
has_many :through ?
You can use “:uniq => true” for any “has_many” (and HABTM) association,
however it is most useful for “:through” types since direct associations
that need to be unique collections can be handled in the model
validation to prevent duplicates in the first place.