简体   繁体   English

使用Rails关联方法与范围

[英]Using Rails association methods versus scopes

When is it appropriate (if ever) to use association methods instead of scopes? 什么时候(如果有的话)使用关联方法而不是范围? Here's an example that I think warrants association methods over scopes: 我认为这是一个值得在范围上进行关联的方法的示例:

I want to be able to get the current, complete accreditation for a user by invoking something like user.accreditations.current . 我希望能够通过调用诸如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

This strategy feels better because the 'current' method is defined in the User model where it is relevant. 这种策略感觉更好,因为在用户模型中相关的地方定义了“当前”方法。 Calling Accreditation.current isn't really relevant because there is no notion of currentness without the User to provide context. 调用Accreditation.current并不是真正相关的,因为没有用户提供上下文就没有当前性的概念。

Here is the same result using scopes: 这是使用范围的相同结果:

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

Maybe? 也许? Seems like there a few ways to skin a cat. 好像有几种方法可以给猫皮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM