[英]Ruby on Rails create model attribute with options to select from
是否可以使用某些选项创建Rails ActiveRecord属性? 这就是我的意思。 假设我们有一个称为Article的模型,它定义了博客文章。 其中一个属性表示该文章是带有图像的帖子,或者是具有图像的帖子,或者是具有纯文本的帖子。 每个选项将触发不同的布局以进行渲染。 属性具有一定数量的预定义选项。
如何将这样的属性“发布类型”添加到模型中?
您的案例似乎需要实现多态 。 你可以做类似的事情
class Article < ActiveRecord::Base
belongs_to :articleable, polymorphic: true
end
class Post < ActiveRecord::Base
has_many :articles, as: :articleable
end
class PlainText < ActiveRecord::Base
has_many :articles, as: :articleable
end
#Migration
class CreateArticless < ActiveRecord::Migration
def change
create_table :articles do |t|
t.string :name
t.integer :articleable_id
t.string :articleable_type
t.timestamps
end
end
end
因此,基本上您将只有一个articles表,并且“ articleable_type”将存储它是哪种类型的Article
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.