Question

This is probably simple for most of you out there, I however havent really written many scopes that have multiple arguments, single arguments are fine, just unsure here. I am trying to create a scope that says "Give me all the books that the current user has checked out"

So I have come up with this in my book model

scope :checked_out_book, lambda{|user| { :conditions => { :user_id => current_user.id, :checked_out => true } }

Haven’t used lambda before so unsure if i am using it correctly, either way i am getting the error

syntax error, unexpected keyword_end, expecting '}'

Can anyone point me in the right direction

EDIT

Have changed scope to

scope :checked_out_book, lambda {|user| where(:user_id => user.id, :checked_out => true) }

but now i get

wrong number of arguments (0 for 1) Thanks

Was it helpful?

Solution

I'd do it like this:

scope :checked_out_book, lambda {|user| where(:user_id => user.id, :checked_out => true) }

OTHER TIPS

scope :checked_out_book, lambda {|user| where(:user_id => user.id, :checked_out => true) }

On the Book model, the scope should be like this:

scope :checked_out_book, lambda {|user| where(:user_id => user.id, :checked_out => true) }

or for Ruby 1.9

scope :checked_out_book, ->(user) { where(user_id: user.id, checked_out: true) }

And you would call it like this:

Book.checked_out_book(current_user)

Now since User has_many Books, I would probably go with something like this and don't bother with scopes. If you want a method like approach, you can always create a method that returns a Relation object.

current_user.books.where(checked_out: true)

or

def checked_out_books
  books.where(checked_out: true)
end
# current_user.checked_out_books
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top