Scopes in Rails 3
Scopes in Rails 3
19 February 2011
Scopes have become much more useful in Ruby on Rails 3 with the adoption ofArel into ActiveRecord. The first and mostobvious benefit related to scopes is that everything is scoped! That means youno longer have to use find(...) on an ActiveRecord model and have a queryimmediately be executed. You can actually build queries up and only executethem when you use them. For example:
In Rails 2.x the find method worked like this: User.find(
:all,
:joins => :profile,
:conditions => ['profile.age = ?', 33])
This would then execute the query and find all users with age 33. In Rails 3.xthis is much simpler: User.joins(:profile).where('profile.age = ?', 33)
Not only is this more readable since you don't have to put your entire queryinto a single function call, but the main difference between these two commandsis that the second doesn't execute a query. You actually have to call .all,.count, .each or .first to get the query to execute. What's great about that?Well, it means you can chain conditions together before you execute them: query = User.joins(:profile).where('profile.age = ?', 33)
query.where('users.name = ?', name) unless name.nil?
query.where('profile.email = ?', email) unless email.nil?
query.all
This really shines when you combine it with scopes. For instance, if we want tosimplify the above code, we can do the following: class User
scope :by_age, lambda do |age|
joins(:profile).where('profile.age = ?', age) unless age.nil?
end
scope :by_name, lambda{ |name| where(name: name) unless name.nil? }
scope :by_email, lambda do |email|
joins(:profile).where('profile.email = ?', email) unless email.nil?
end
end
User.by_age(33).by_name(params[:name]).by_email(params[:email]).all
Isn't that just awesome!? Not only is the code easier to read and understand,but it's re-usable and scoped! Here's one more example: class Tag
belongs_to :post
end
class Post
has_many :tags
belongs_to :user
scope :tagged, lambda do |tag|
joins(:tags).where('tags.name = ?', tag).group('posts.id')
end
end
class User
has_many :posts
end
# How many of my posts are tagged with 'ruby-on-rails'?
User.where('users.id = ?', 232423).posts.tagged('ruby-on-rails').count
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
ios background location update
About positioning
There are three official recommendations
The significant-change location service (Recommended)
Foregro...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.
User.find(
:all,
:joins => :profile,
:conditions => ['profile.age = ?', 33])
User.joins(:profile).where('profile.age = ?', 33)
query = User.joins(:profile).where('profile.age = ?', 33)
query.where('users.name = ?', name) unless name.nil?
query.where('profile.email = ?', email) unless email.nil?
query.all
class User
scope :by_age, lambda do |age|
joins(:profile).where('profile.age = ?', age) unless age.nil?
end
scope :by_name, lambda{ |name| where(name: name) unless name.nil? }
scope :by_email, lambda do |email|
joins(:profile).where('profile.email = ?', email) unless email.nil?
end
end
User.by_age(33).by_name(params[:name]).by_email(params[:email]).all
class Tag
belongs_to :post
end
class Post
has_many :tags
belongs_to :user
scope :tagged, lambda do |tag|
joins(:tags).where('tags.name = ?', tag).group('posts.id')
end
end
class User
has_many :posts
end
# How many of my posts are tagged with 'ruby-on-rails'?
User.where('users.id = ?', 232423).posts.tagged('ruby-on-rails').count
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
ios background location updateAbout positioning There are three official recommendations The significant-change location service (Recommended) Foregro...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.