---
title: "Rails 3 的 scope"
author: "夜鸣猪"
date: "2012-03-06T11:08:43Z"
tags: ["Rails", "conditions", "joins"]
categories: ["编程语言"]
slug: "rails-3-scope"
draft: false
lastmod: "2012-03-06T11:08:43Z"
id: 1441419
url: "https://hlee.iteye.com/blog/1441419"
---

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

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

```

在rails 3中变成如下

```ruby
User.joins(:profile).where('profile.age = ?', 33)
```

区别在于，后者可以跟each，all，count， first

```ruby

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

```ruby

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

```


当然还有重用


```ruby
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
```