Modeling Relationships with Four or More Models in Rails -
i have these models in rails app:
group.rb has_many :group_members has_many :group_foo_types group_member.rb # fields :group_id, :user_id belongs_to:group has_many :group_foo_types, :through=>:groups has_one :user has_many :foo, :through=>:user has_many :bar, :through=>:user group_foo_type.rb # fields :group_id, :foo_type_id belongs_to :group belongs_to :foo_type user.rb has_many :foo has_many :bar foo.rb # fields :user_id, :foo_type_id belongs_to :user belongs_to :foo_type bar.rb # fields :user_id, :foo_type_id belongs_to :user belongs_to :foo_type
what i'm trying is, group, find foos , bars per user taking account foo_type_id group (from group_foo_type).
however, i'm not sure if have modeled correctly.
from this, seems can group.group_members.user
users , user.foos' , 'user.bars
user's foos , bars. doesn't take account foo_type_id
group
though (from group_foo_type
).
can please recommend approach accomplish want do? thank you!
as mentioned in this answer, since rails 3.1 can nest has_many :through
associations. have easy access of group's foos , bars, add following associations:
# group.rb has_many :users, through: :group_members has_many :foos, through: :users has_many :bars, through: :users
with this, group.foos
give of group's foos (via group_member
, user
).
the association methods in rails can used various finder methods, limit foos group_foo_type
:
group_foos = group.foos.where(foo_type_id: group.group_foo_type_ids)
(group_foo_type_ids
being useful association method, check association basics guide more info.)
a caution: there lot of steps have go on in background achieve of stuff, if relatively easy code. may want keep eye on queries generated (either through console or logs) , how perform, they're involved. looks have complex set of associations there, may worth looking @ whether can simplify there. keep in mind!
Comments
Post a Comment