简体   繁体   中英

Ruby on Rails create model attribute with options to select from

Is it possible to create Rails ActiveRecord attribute with some sort of options? Here is what I mean. Let's say we have a model called Article which defines blog 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

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. 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 . For example:

In your View

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM