【问题标题】:Scopes to separate polymorphic relationships用于分离多态关系的范围
【发布时间】:2016-04-08 10:27:11
【问题描述】:

我在 Rails 4 项目中有以下数据库关系

class Hat < ActiveRecord::Base
  belongs_to :sale, as: product
end

class Shoe < ActiveRecord::Base
  belongs_to :sale, as: product
end

class Sale < ActiveRecord::Base
  has_many :products, polymorphic: true

  scope :hats, -> { ??? }
  scope :shoes, -> { ??? }
end

给定一个@sale 对象,我如何获得属于特定型号的所有产品,例如HatShoe

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 activerecord rails-activerecord


    【解决方案1】:

    您的表中应该有一个product_type(有关更多信息,请参阅the guides),所以我会对此进行查询:

    scope :hats, -> { where(product_type: Hat.name) }
    # Not sure that this `Hat.class.name` is the actual value in the table, 
    # so you might aswell check in your DB what's the correct value.
    

    【讨论】:

    • Hat.class.name 呈现Class
    猜你喜欢
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 2015-12-07
    • 2012-05-10
    • 1970-01-01
    相关资源
    最近更新 更多