How do you use Active Record Enum Radio Buttons in a form?

LMo picture LMo · Jul 31, 2014 · Viewed 8k times · Source

In my app, there is a comment section on articles. I'd like the user to have the ability to comment with 3 different options. To activate this, I am using an Active Record Enum. Please note that the comment sections is nested under the articles.

resources :articles, only: [:index, :show] do
  resources :comments
end

Migration:

class AddEnumToCommentModel < ActiveRecord::Migration
  def change
    add_column :comments, :post_as, :integer, default: 0
  end
end

Comment model:

enum post_as: %w(username, oneliner, anonymous)

I attempted to add this to the content view, but lost. I am guessing I also have to do something in my controller but not sure.

Attempted view :

<%= form_for([@article, @comment]) do |f| %>
  <% if @comment.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@comment.errors.count, "error") %> prohibited this comment from being saved:</h2>

      <ul>
      <% @comment.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <h3>Fill in your comment</h3>
    <%= f.label :content %><br>
    <%= f.text_area :content %>
  </div>

  <div class="post_as">
    <h3> Choose how you want to post your comment :</h3>
    <%= f.input :content, post_as: ???, as: :radio %>
  </div>

  <br>

  <div class="actions">
    <%= f.submit %>
  </div>

  <br>
<% end %>

Answer

xxyyxx picture xxyyxx · Oct 24, 2014

Rails creates a class method using the pluralized attribute name when you use enum. The method returns a key value pair of strings you've defined and what integers they map to. So, you could do something like this:

<% Comment.post_as.keys.each do |post_as| %>
  <%= f.radio_button :post_as, post_as %>
  <%= f.label post_as.to_sym %>
<% end %>