【发布时间】:2013-12-22 18:35:44
【问题描述】:
什么时候适合(如果有的话)使用关联方法而不是作用域?这是一个我认为在范围内保证关联方法的示例:
我希望能够通过调用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
【问题讨论】:
标签: ruby-on-rails scopes