如何在表单中使用Active Record枚举单选按钮?

16
在我的应用程序中,文章下有一个评论区。我希望用户可以使用三个不同的选项进行评论。为了实现这一点,我正在使用Active Record Enum。请注意,评论部分是嵌套在文章下面的。
resources :articles, only: [:index, :show] do
  resources :comments
end

迁移:

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

评论模型:

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

我尝试将这个添加到内容视图中,但失败了。我猜我还需要在控制器中做一些事情,但不确定。

尝试的视图:

<%= 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 %>
4个回答

23
Rails在使用enum时,将创建一个使用复数形式的属性名称的类方法。该方法返回您定义的字符串和它们映射到的整数的键值对。因此,您可以像这样操作:
<% Comment.post_as.keys.each do |post_as| %>
  <%= f.radio_button :post_as, post_as %>
  <%= f.label post_as.to_sym %>
<% end %>

7

此外还有 collection_radio_buttons,比其他选项更为简洁。

<%= f.collection_radio_buttons :post_as, Comment.post_as, :second, :first %>

最后两个参数指定如何获取输入的值和标签文本。在你的例子中,Comment.post_as 生成一个枚举键名到底层整数的哈希表,所以我们可以使用 :second 来获取整数,使用 :first 来获取名称 - 简单!

以下是它的输出结果:

<input type="radio" value="0" name="comment[post_as]" id="comment_post_as_0">
<label for="comment_post_as_0">username</label>
# Etc.

您可以通过传递一个块来自定义HTML,这是我创建带有可点击标签的枚举单选按钮的首选方式:
<%= f.collection_radio_buttons :post_as, Comment.post_as, :second, :first do |b|
  b.label { b.radio_button + b.text }
end %>

6

对于 xxyyxx 的答案,如果您想让标签也可点击:

<% Comment.post_as.keys.each do |post_as| %>
  <%= f.radio_button :post_as, post_as %>
  <%= f.label "#{:post_as}_#{post_as.parameterize.underscore}", post_as %>
<% end %>

4
在视图中代替
<%= f.input :content, post_as: ???, as: :radio %>

你可以有
<%= f.radio_button(:post_as, "username") %>
<%= label(:post_as, "Username") %>
<%= f.radio_button(:post_as, "oneliner") %>
<%= label(:post_as, "Oneline") %>
<%= f.radio_button(:post_as, "anonymous") %>
<%= label(:post_as, "Anonymous") %>

来源:http://guides.rubyonrails.org/form_helpers.html#radio-buttons

这是一个关于使用Ruby on Rails中的表单帮助程序来创建单选按钮的指南。在Rails中,可以使用“radio_button”辅助方法来创建单选按钮。该方法接受四个参数:对象名称、属性名称、值和HTML选项哈希。通过指定不同的值,可以创建多个单选按钮,只有一个按钮被选中。为了让用户知道哪个选项被选中,可以将“checked”选项设置为true。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接