0

考虑少女模特儿包括Model:Rails的:基于列的值

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

Book 
    ...attributes 

Magazine 
    ...attributes 

凡产品HAS_ONE书,产品HAS_ONE杂志,书籍belongs_to的产品,书籍杂志belongs_to的。

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

有没有更好的方法来做到这一点,因为书和杂志是一个产品的实例,但有自己非常不同的属性?

回答

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 

更多详细信息请点击链接。

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