繁体   English   中英

使用Rails关联方法与范围

[英]Using Rails association methods versus scopes

什么时候(如果有的话)使用关联方法而不是范围? 我认为这是一个值得在范围上进行关联的方法的示例:

我希望能够通过调用诸如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

这种策略感觉更好,因为在用户模型中相关的地方定义了“当前”方法。 调用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
class User < ActiveRecord::Base
  has_one :current_accreditation, -> { where(state: 'complete').order(:created_at).last }, source: :accreditations
end

也许? 好像有几种方法可以给猫皮。

暂无
暂无

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

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