ITeye博客

Rails 3 的 scope

夜鸣猪 · 2012-03-06 11:08 · Ruby On Rails · 编程语言 · Rails · joins · conditions · Markdown

在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?
  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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。