简体   繁体   中英

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(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

{"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?

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

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

interpreted from the documentation at 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):

  <% @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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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