简体   繁体   English

Ruby on Rails创建模型属性,并提供可供选择的选项

[英]Ruby on Rails create model attribute with options to select from

Is it possible to create Rails ActiveRecord attribute with some sort of options? 是否可以使用某些选项创建Rails ActiveRecord属性? Here is what I mean. 这就是我的意思。 Let's say we have a model called Article which defines blog article. 假设我们有一个称为Article的模型,它定义了博客文章。 One of the attributes says that this article is a post with image, or a post with image, or a post with plain text. 其中一个属性表示该文章是带有图像的帖子,或者是具有图像的帖子,或者是具有纯文本的帖子。 Each option will trigger different layout to render. 每个选项将触发不同的布局以进行渲染。 Attribute has certain number of predefined options. 属性具有一定数量的预定义选项。

How can I add such attribute "post type" to a model? 如何将这样的属性“发布类型”添加到模型中?

Your case looks like a need for implementing Polymorphism . 您的案例似乎需要实现多态 You can do something like 你可以做类似的事情

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

So essentially you will have a single articles table and the 'articleable_type' will be storing what type of Article is it 因此,基本上您将只有一个articles表,并且“ articleable_type”将存储它是哪种类型的Article

Implementing a polymorphic object, as @ankitg suggests, is the way to go if you want your objects to behave differently across different parts of your system. 如@ankitg所建议,实现多态对象是您希望对象在系统的不同部分之间表现不同的一种方式。 However, this approach may work for you if you just need a little bit of custom content in your view. 但是,如果您只需要视图中的一些自定义内容,则此方法可能对您有用。

You can add an attribute to your model called post_type and then render different html, in the view, depending on the post_type . 您可以在模型中添加一个名为post_type 的属性 ,然后在视图中根据post_type呈现不同的html。 For example: 例如:

In your View 在您看来

<% 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