Rails 3 的 scope

在rails 2中关联俩个表时如下用:

User.find(
:all,
:joins => :profile,
:conditions => ['profile.age = ?', 33])

在rails 3中变成如下
User.joins(:profile).where('profile.age = ?', 33)

区别在于,后者可以跟each,all,count, first

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

因为有了AREL的支持
[url]https://github.com/rails/arel[/url]

最大的优势是组合和lazy loading

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

# 标记为 'ruby-on-rails',并且是特定user的帖子
User.where('users.id = ?', 232423).posts.tagged('ruby-on-rails').count
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值