Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First or limit in Rails scope

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.

like image 875
Victor Avatar asked Oct 25 '12 14:10

Victor


People also ask

How do scopes work in Rails?

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.

What are default scopes in Rails?

A default scope is one which is automatically applied to your model.

What are active records in Rails?

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.


1 Answers

@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.

like image 167
Tom L Avatar answered Sep 20 '22 22:09

Tom L