简体   繁体   English

使用Rails Action View帮助器时,如何自定义参数使其成为标签数组?

[英]When using rails Action View Helpers - how can you customize the params to be an Array of the labels?

I have this view 我有这个看法

...code....

      <% @feeds.each do |feed| %>
        <%= check_box_tag(feed.name) %>
        <%= label_tag(feed.name) %>
      <% end %>

...code....

The Feed model looks like this Feed模型如下所示

Feed(id: integer, name: string, description: string, url: string, created_at: datetime, updated_at: datetime, day_selector: string, special_selector: string)

and the submission comes into the params hash like this 提交像这样进入params哈希

{"utf8"=>"✓",
 "authenticity_token"=>"WVbxZckIJCA0dXqPZGnSXJi7yrDN3Ssttv7dnJZOfBY=",
 "email"=>"",
 "phone_number"=>"",
 "Squeaky Beaker"=>"1",
 "Commonwealth Cambridge"=>"1",
 "commit"=>"GO",
 "action"=>"create",
 "controller"=>"subscriptions"}

I want the params hash to look this this 我希望参数哈希看起来这个

{:feeds => {'Squeaky Beaker' => 1, 'Commonwealth Cambridge' => 1}}

or just simply 或者只是

[{'Squeaky Beaker' => 1, 'Commonwealth Cambridge' => 1}]

How can I customize my view to have the params hash look the way I want? 如何自定义视图以使params哈希看起来像我想要的方式?

untested, but you could try... 未经测试,但您可以尝试...

<ul>
  <% @feeds.each do |feed| %>
      <li>
        <%= check_box_tag 'feeds[]', (feed.name => 1) -%>
        <%= h feed.name -%>
      </li>
  <% end %>
</ul>

I'm not sure the => 1 has value to your application, so the more traditional approach would be 我不确定=> 1对您的应用程序是否有价值,因此更传统的方法是

        <%= check_box_tag 'feeds[]', feed.name -%>

interpreted from the documentation at http://apidock.com/rails/ActionView/Helpers/FormTagHelper/check_box_tag http://apidock.com/rails/ActionView/Helpers/FormTagHelper/check_box_tag的文档解释

Check Box 复选框

To further SteveTurczyn 's answer, what you're basically doing right now is outputting two checkboxes (completely different to each other), which will both hold a value of "1" (checked): 为了进一步说明SteveTurczyn的答案,您现在基本上正在执行的操作是输出两个checkboxes (彼此完全不同),两个checkboxes的值都为“ 1”(已选中):

  <% @feeds.each do |feed| %>
    <%= check_box_tag(feed.name) #-> feed.name will be different each time %>
    <%= label_tag(feed.name) %>
  <% end %>

You'll need to give the check boxes the same name, as to give Rails the ability to discern their values being different. 您需要为复选框赋予相同的名称,以使Rails能够辨别其值是否不同。 And secondly, you'll need to ensure you have the correct vales / options for the boxes too: 其次,您还需要确保盒子也具有正确的价位/选项:

<% @feeds.each do |feed| %>
   <%= check_box_tag "feeds[]", feed.name %>
<% end %>

This will pass the parameters as follows: 这将通过如下参数:

["checked_value_1", "checked_value_2"]

If you use the names of the feeds, it will give you: 如果使用提要的名称,它将为您提供:

["Feed1", "Feed2"] #-> names
["5", "6", "7" ] #-> ids

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM