[英]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.