Rails:根据列值包含模型

时间:2017-03-15 18:58:01

标签: ruby-on-rails activerecord database-design rails-activerecord

考虑伪模型:

Product  
  id  
  type - enumerable 'book' or 'magazine'  

Book  
  ...attributes  

Magazine  
  ...attributes  

产品has_one Book,Product has_one Magazine,Book belongs_to Product,Book belongs_to Magazine。

如何根据Product.type(书籍或杂志)选择型号(书籍或杂志)?

有没有更好的方法来实现这一点,因为Book and Magazine是产品的实例,但它们有不同的属性?

2 个答案:

答案 0 :(得分:1)

请参阅Rails'Polymorphic Associations。例如:

class Product < ActiveRecord::Base
  belongs_to :buyable, polymorphic: true
end

class Book < ActiveRecord::Base
  has_one :product, as: :buyable
end

class Magazine < ActiveRecord::Base
  has_one :product, as: :buyable
end

链接上有更多细节。

答案 1 :(得分:0)

我认为bellow代码段对您有所帮助。

class Product < ApplicationRecord
 enum type: [:book, :magazine]  
end

class Book < Product
  before_create :set_type

  private 
  def set_type  
   self.type = :book.to_s
  end
end

class Magazine < Product
  before_create :set_type  

  private 
  def set_type  
    self.type = :magazine.to_s
 end  
end