Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 scope with argument

Tags:

Upgrading Rails 3.2. to Rails 4. I have the following scope:

# Rails 3.2 scope :by_post_status, lambda { |post_status| where("post_status = ?", post_status) } scope :published, by_post_status("public") scope :draft, by_post_status("draft")  # Rails 4.1.0 scope :by_post_status, -> (post_status) { where('post_status = ?', post_status) } 

But I couldn't find out how to do the 2nd and 3rd lines. How can I create another scope from the first scope?

like image 446
Victor Avatar asked May 01 '14 17:05

Victor


People also ask

What is scope in ActiveRecord?

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.

How does scope work in Rails?

Scopes are custom queries that you define inside your Rails models with the scope method. Every scope takes two arguments: A name, which you use to call this scope in your code. A lambda, which implements the query.

What is difference between scope and class method Rails?

Scopes are just class methods. Internally Active Record converts a scope into a class method. "There is no difference between them" or “it is a matter of taste”.

How do you name a scope in Rails?

Like Ruby class methods, to invoke the named scopes, simply call it on the class object. Named scopes takes two arguments; name and lambda. Use an expressive name. Lambda is a block of code.


1 Answers

Very simple, just same lambda without arguments:

scope :by_post_status, -> (post_status) { where('post_status = ?', post_status) } scope :published, -> { by_post_status("public") } scope :draft, -> { by_post_status("draft") } 

or more shorted:

%i[published draft].each do |type|   scope type, -> { by_post_status(type.to_s) } end 
like image 83
Philidor Avatar answered Dec 18 '22 19:12

Philidor