【问题标题】:how to rewrite HTML code in a rails form helper如何在 Rails 表单助手中重写 HTML 代码
【发布时间】:2020-05-05 05:55:22
【问题描述】:

我想为评论模型添加 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>

如何使用辅助导轨,以便在模型字段中:评级是编号为 1 到 5 的条目

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-4 ruby-on-rails-5 helper


【解决方案1】:

尝试以下方法:

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>

会根据您需要的标签和类别来帮助您。

【讨论】:

  • 你试过了吗?它真的可以与哈希一起使用吗?
  • 感谢@max,把 javascript 和 ruby​​ 搞混了。修正了我的答案。
猜你喜欢
  • 1970-01-01
  • 2018-10-26
  • 1970-01-01
  • 1970-01-01
  • 2018-12-06
  • 2011-05-21
  • 2010-12-16
  • 2014-01-26
  • 1970-01-01
相关资源
最近更新 更多