0

I have these models in my 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 to do is, for a group, find the foos and bars per user taking into account the foo_type_id for the group (from group_foo_type).

However, I'm not sure if I have this modeled correctly.

From this, it seems like I can do group.group_members.user to get the users and then user.foos' and 'user.bars to get a user's foos and bars. This doesn't take into account the foo_type_id for the group though (from group_foo_type).

Can someone please help recommend an approach to accomplish what I want to do? Thank you!

yellowreign
  • 3,528
  • 8
  • 43
  • 80

1 Answers1

0

As mentioned in this answer, since Rails 3.1 you can nest has_many :through associations. So to have easy access to all of a group's foos and bars, you could add the following associations:

# group.rb
has_many :users, through: :group_members
has_many :foos, through: :users
has_many :bars, through: :users

With this, group.foos would give you all of the group's foos (via group_member and user).

The association methods in rails can be used with the various finder methods, so to limit the foos by group_foo_type:

group_foos = group.foos.where(foo_type_id: group.group_foo_type_ids)

(group_foo_type_ids being another useful association method, check the Association Basics guide for more info.)

A caution: there are a lot of steps that have to go on in the background to achieve any of this stuff, even if it does get relatively easy to actually code. You may want to keep an eye on the queries that get generated (either through the console or logs) and how they perform, as they're likely to get fairly involved. It looks like you have a fairly complex set of associations there, so it may be worth looking at whether you can simplify anything there. Just something to keep in mind!

Community
  • 1
  • 1
zkcro
  • 4,344
  • 1
  • 24
  • 22