如何在 rails 表单助手中重写 HTML 代码

how to rewrite HTML code in a rails form helper

我想为“评论”模型添加 5 星评级。 我有一个表格:

 <%= form_with(model: [ @product, @product.comments.build ], local: true) do |form| %>
  <p>
    <%= form.label t('activerecord.attributes.comment.commenter') %><br>
    <%= form.text_field :commenter %>
  </p>
  <p>
    <%= form.label t('activerecord.attributes.comment.body') %><br>
    <%= form.text_area :body %>
  </p>
  <p>
    <%= form.submit t('products.form.submit') %>
  </p>
<% end %>

型号:

# Table name: comments
#
#  id         :bigint           not null, primary key
#  body       :text
#  commenter  :string
#  rating     :float
#  created_at :datetime         not null
#  updated_at :datetime         not null
#  product_id :bigint           not null

我想在此表单中添加一个字段 :rating 。

HTML:

<div id="reviewStars-input">
  <input id="star-4" type="radio" value="5" name="reviewStars"/>
  <label title="gorgeous" for="star-4"></label>

  <input id="star-3" type="radio" value="4" name="reviewStars"/>
  <label title="good" for="star-3"></label>

  <input id="star-2" type="radio" value="3" name="reviewStars"/>
  <label title="regular" for="star-2"></label>

  <input id="star-1" type="radio" value="2" name="reviewStars"/>
  <label title="poor" for="star-1"></label>

  <input id="star-0" type="radio" value="1" name="reviewStars"/>
  <label title="bad" for="star-0"></label>
</div>

如何使用助手 rails 以便在模型中 field:rating 条目编号为 1 到 5

尝试如下操作:

class Comment < ApplicationRecord
  STARS = [
    [5, 'gorgeous'],
    [4, 'good'],
    [3, 'regular'],
    ...
  ]

<div id="reviewStars-input">
  <%= collection_radio_buttons(:comment, :rating, Comment::STARS, :first, :second) do |b| %>
    <%= b.radio_button %>
    <%= b.label( title: b.text ) %>
  <% end %>
</div>

将根据您需要的标签和 类 让您关闭。