【问题标题】:Using Rails association methods versus scopes使用 Rails 关联方法与范围
【发布时间】: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


    【解决方案1】:
    class User < ActiveRecord::Base
      has_one :current_accreditation, -> { where(state: 'complete').order(:created_at).last }, source: :accreditations
    end
    

    也许?似乎有几种方法可以给猫剥皮。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-19
      • 1970-01-01
      • 2013-06-09
      • 1970-01-01
      • 1970-01-01
      • 2016-07-23
      • 2015-06-25
      • 1970-01-01
      相关资源
      最近更新 更多