如何通过使用form_for创建的rails表单传递其他(单选按钮)参数?

问题描述 投票:0回答:2

我有一个form_for帮助器,为我的Image模型创建一个对象。它看起来像这样:

<%= form_for :image, url: images_path do |f| %> 

  <p>
    <%= f.file_field :file %> 
  </p> 

  <p>
    <input type="radio" name="index" value="1">1 
    <input type="radio" name="index" value="2">2
    <input type="radio" name="index" value="3">3
  </p>

  <p><%= f.submit "submit" %></p> 
<% end %> 

在观察了params散列后,:file文件按预期传递。我还需要在单选按钮中传递值,或者至少,我需要知道图像控制器的create函数中该值是什么。如何通过params哈希(或通过其他方式)传递此值?

ruby-on-rails ruby form-for
2个回答
2
投票

您可以将单选按钮的name属性更改为此image[index]

更好的方法(IMO)是使用实例变量来存储这样的值,因为它允许你编写像f.radio_button :index这样的代码。

例如

class Image < ActiveRecord::Base
   attr_accessor :index
   # Uncomment if you're using Rails < 4, otherwise whitelist the attr in the controller
   #attr_accessible :index 
end

另一方面,考虑使用像radio_button_tag这样的表单助手,比纯HTML更好。


0
投票

在form_for中,您可以执行以下操作:

<p>
   <%= f.radio_button_tag(:index, "1") %>
   <%= f.label_tag(:index_1, "1") %>
   <%= f.radio_button_tag(:index, "2") %>
   <%= f.label_tag(:index_2, "2") %>
   <%= f.radio_button_tag(:index, "3") %>
   <%= f.label_tag(:index_3, "3") %>
</p>
© www.soinside.com 2019 - 2024. All rights reserved.