LoginSignup
2
2

More than 5 years have passed since last update.

Rails4 | 新規・変更機能 | 名前付きscopeはlambda記法のみを許容

Last updated at Posted at 2014-06-25

Rails4 | 新規・変更機能 | 名前付きscopeはlambda記法のみを許容

概要

Rails3以前では名前付き scope には2通りの記法がありました。

class SomeModel < ActiveRecord::Base
  # lambdaを使わない記法
  scope :scope_name, where('condition > 10')
  default_scope where('condition > 20')
  # lambdaを使う記法
  scope :scope_name, -> { where('condition > 10') }
  default_scope { where('condition > 10') }
end

Rails4では lambda記法 のみを許容します。
(実行タイミングの誤解を防ぐため)

サンプル

仕様

  • 下記で scaffold した状態をベースとする
rails g scaffold person name:string age:integer
rake db:migrate

テーブルには以下のデータが登録されています

$ select * from people;
1|tanaka|20|2014-06-25 23:45:12.555117|2014-06-25 23:15:55.737728
2|suzuki|19|2014-06-25 23:45:30.476800|2014-06-25 23:15:50.489037

サンプルコード

  • scaffold した状態の PeopleControllerindex メソッドを下記のように変更します
  def index
    case params['age_type']
    when 'minority'
      @people = Person.minority
    when 'adult'
      @people = Person.adult
    else
      @people = Person.all
    end
  end
  • Personモデルに scope の設定を追加します
class Person < ActiveRecord::Base
  scope :adult, -> { where('age >= 20') }
  scope :minority, -> { where('age < 20') }
end

成人のデータをリクエストする

画面には以下のようなレコードが表示されます

tanaka  20  Show  Edit  Destroy

未成年のデータをリクエストする

画面には以下のようなレコードが表示されます

suzuki  19  Show  Edit  Destroy

成人・未成年をリクエスト

画面には以下のようなレコードが表示されます。

tanaka  20  Show  Edit  Destroy
suzuki  19  Show  Edit  Destroy
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2