0

スコープの代わりに関連付けメソッドを使用するのが適切なのはいつですか? これは、スコープを介した関連付けメソッドを正当化すると私が考える例です。

のようなものを呼び出して、ユーザーの現在の完全な認定を取得できるようにしたいと考えていますuser.accreditations.current

class User < ActiveRecord::Base
  has_many :accreditations do
    def current
      where(state: 'complete').order(:created_at).last
    end
  end
end

class Accreditations < ActiveRecord::Base
  belongs_to :user
end

この戦略は、「現在の」メソッドが関連する User モデルで定義されているため、より適切に感じられます。Accreditation.current の呼び出しは、コンテキストを提供するユーザーなしでは現在の概念がないため、実際には関係ありません。

スコープを使用した同じ結果を次に示します。

class Accreditations < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :accreditations

  scope :current, -> { where(state: 'complete').order(:created_at).last }
end
4

1 に答える 1

0
class User < ActiveRecord::Base
  has_one :current_accreditation, -> { where(state: 'complete').order(:created_at).last }, source: :accreditations
end

多分?猫の皮を剥く方法はいくつかあるようです。

于 2013-12-05T17:36:29.373 に答える