I have the following scope:
scope :user_reviews, lambda { |user| where(:user_id => user) }
I apply this in the controller:
def show
@review = @reviewable.reviews.user_reviews(current_user).first || Review.new
end
The first
is to limit to search the current user's one and only review. Now I try to write a new scope user_review
which I tried many ways to chain the user_reviews
scope with first
, but just couldn't get it what. Something like this:
scope :user_reviews, lambda { |user| where(:user_id => user) }
scope :user_review, lambda { |user| user_reviews(user).first }
I know the above user_review
is wrong, but just trying to show you guys what I am trying to do.
How should I write this properly?
Thanks.
Scopes are used to assign complex ActiveRecord queries into customized methods using Ruby on Rails. Inside your models, you can define a scope as a new method that returns a lambda function for calling queries you're probably used to using inside your controllers.
A default scope is one which is automatically applied to your model.
Rails Active Records provide an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables.
@Victor, just stick with your original idea. Use scope :user_reviews, lambda { |user| where(:user_id => user) }
and call user_reviews.first
. Nothing wrong with that.
Definitely do not define a scope that returns a single object. A scope should be chainable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With