Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scoped and scope in rails

Can somebody explain what this method does and what I can pass to it?

scoped(options = nil)
Returns an anonymous scope.

And also what the scope method does? I don't understand after reading the documentation.

like image 659
LuckyLuke Avatar asked Aug 10 '12 10:08

LuckyLuke


People also ask

What are scope in Rails?

What is a scope in Rails & why is it useful? 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.

What is scope method in Ruby?

Scope defines where in a program a variable is accessible. Ruby has four types of variable scope, local, global, instance and class. In addition, Ruby has one constant type. Each variable type is declared by using a special character at the start of the variable name as outlined in the following table.

What are active records in Rails?

1 What is Active Record? Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

What is include in Rails?

Rails provides an ActiveRecord method called :includes which loads associated records in advance and limits the number of SQL queries made to the database. This technique is known as "eager loading" and in many cases will improve performance by a significant amount.


1 Answers

In ActiveRecord, all query building methods (like where, order, joins, limit and so forth) return a so called scope. Only when you call a kicker method like all or first the built-up query is executed and the results from the database are returned.

The scoped class method also returns a scope. The scope returned is by default empty meaning the result set would not be restricted in any way meaning all records would be returned if the query was executed. You can use it to provide an "empty" alternative like in the query_by_date example by MurifoX. Or you can use it to combine multiple conditions into one method call, like for example:

Model.scoped(:conditions => 'id < 100', :limit => 10, :order => 'title ASC')

# which would be equivalent to
Model.where('id < 100').limit(10).order('title ASC')

The scope class method allows you to define a class method that also returns a scope, like for example:

class Model
  scope :colored, lambda {|col|
    where(:color => col)
  }
end

which can be used like this:

Model.colored

The nice thing with scopes is that you can combine them (almost) as you wish, so the following is absolutely possible:

Model.red.where('id < 100').order('title ASC').scoped(:limit => 10)

I also strongly suggest reading through http://guides.rubyonrails.org/active_record_querying.html

like image 160
severin Avatar answered Sep 22 '22 13:09

severin