繁体   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