Rails 5 - how to write a scope Rails 5 - how to write a scope ruby ruby

Rails 5 - how to write a scope


You'll need to pass user or user_id in as an argument when you call the scope. You can define it like this:

scope :proponent,   ->(user){ where(user_id: user.id) }

or

def self.proponent(user)  where user_id: user.idend

These really are the same thing.

Then calling it:

Proposal.proponent(user)# => returns a list of proposals for the specific user

Note this is the same thing as saying

proposal = Proposal.find_by(...)proposal.user.proposals