Using named_scopes in a has_many join model: via

I hit my head against a wall over something that should be very simple on the surface. Suppose I have the following simplified models:

user.rb

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

membership.rb

belongs_to :group  
belongs_to :user  
STATUS_CODES = {:admin => 1, :member => 2, :invited => 3}  
named_scope :active, :conditions => {:status => [[STATUS_CODES[:admin], STATUS_CODES[:member]]}

group.rb

has_many :memberships  
has_many :users, :through => :memberships

Simple, right? Therefore, I want to get a collection of all groups in which the user is active, using the existing named area in the connection model. Something like User.find (1) .groups.active lines. Obviously this does not work.

But since that is the case, I need to do something like User.find(1).membrships.active.all(:include => :group)that which returns a collection of membership plus groups. I do not want it.

I know that I can add another has_many to the User model with conditions that duplicate: active named_scope in the Membership model, but this is rude.

has_many :active_groups, :through => :memberships, :source => :group, :conditions => ...

, : ? .

+3
1

,

User.find(1).memberships.active.collect(&:group)

, .

0

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


All Articles