スコープの代わりに関連付けメソッドを使用するのが適切なのはいつですか? これは、スコープを介した関連付けメソッドを正当化すると私が考える例です。
のようなものを呼び出して、ユーザーの現在の完全な認定を取得できるようにしたいと考えています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