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?
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.
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.
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”.
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.
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
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