What is the easiest way to find a join model, given two objects when using has_many: via

I use has_many :throughto indicate a many-to-many relationship between two objects, and I want to make it easy to get the model from the connection table. Here are the main objects:

class Group < ActiveRecord::Base
    has_many :memberships
    has_many :members, :through => :memberships
end 

class Member < ActiveRecord::Base
    has_many :memberships
    has_many :groups, :through => :memberships
end 

The connection table is called "memberships" and has the additional attribute "admin", which indicates that the user can act as the group administrator for this group. Here's a snapshot of the migration:

create_table :memberships do |t|
  t.integer :group_id
  t.integer :member_id
  t.boolean :admin

  t.timestamps
end

Now, in my controller, I want to check if a particular item is a group administrator. I currently have the following code (which works):

membership = @member.memberships.find_by_group_id(@group.id)

: (), find_by_group_id?

+3
2

Avoding, :

  @member.admin?(@group)

- (!).

  class Member < ActiveRecord::Base

    has_many :memberships
    has_many :groups, :through => :memberships
    named_scope :admin?, :through => :memberships, 
    lambda {|group|:conditions=> ["admin = 'true' and group_id = ?"], group.id }
  end
+4

:

  @member.is_admin?(@group)

- .

  class Member < ActiveRecord::Base

    has_many :memberships
    has_many :groups, :through => :memberships

    def is_admin?(group)
      memberships.find_by_group_id(group.id).admin?
    end

  end
+4

Source: https://habr.com/ru/post/1709083/


All Articles