Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5 - how to write a scope

I am trying to learn how to write scopes in Rails 5.

I have a user model and a proposal model. The associations are:

User:

has_many :proposals

Proposal:

belongs_to :user

In my proposal model, Im trying to figure out how to write a scope that finds the proposals that belong to the user that created them.

I am trying:

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

I have tried a million variations on this but I can't find one that works.

This particular attempt gives this error:

2.3.1p112 :001 > Proposal.proponent
NameError: undefined local variable or method `user' for Proposal (call 'Proposal.connection' to establish a connection):Class

I have also tried:

scope :proponent, -> { where('proposal.user_id = ?', user.id) }

The error I get from this attempt is:

undefined local variable or method `user' for #<Class:0x007fd3600eb038>

I don't know if the error message means the first or second time that I wrote 'user' in my attempt is incorrect. I don't know what "call 'Proposal.connection' means".

Can anyone see what I need to be able to do in order to check the proposals table to find the ones that belong to a specific user?

like image 703
Mel Avatar asked Dec 17 '16 00:12

Mel


1 Answers

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.id
end

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
like image 177
max pleaner Avatar answered Oct 22 '22 17:10

max pleaner