首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网络技术 > 网络基础 >

Rails 三 的 scope

2012-08-25 
Rails 3 的 scope在rails 2中关联俩个表时如下用:User.find(:all,:joins :profile,:conditions [pr

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的支持
https://github.com/rails/arel

最大的优势是组合和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?  endendUser.by_age(33).by_name(params[:name]).by_email(params[:email]).all


当然还有重用

class Tag  belongs_to :postendclass Post  has_many :tags  belongs_to :user  scope :tagged, lambda do |tag|    joins(:tags).where('tags.name = ?', tag).group('posts.id')  endendclass User  has_many :postsend# 标记为 'ruby-on-rails',并且是特定user的帖子User.where('users.id = ?', 232423).posts.tagged('ruby-on-rails').count

热点排行