簡體   English   中英

Ruby on Rails創建模型屬性,並提供可供選擇的選項

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

如@ankitg所建議,實現多態對象是您希望對象在系統的不同部分之間表現不同的一種方式。 但是,如果您只需要視圖中的一些自定義內容,則此方法可能對您有用。

您可以在模型中添加一個名為post_type 的屬性 ,然后在視圖中根據post_type呈現不同的html。 例如:

在您看來

<% if article.post_type == 'image' %>
  <!-- some code -->
<% else %>
  <!-- some other code -->

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM