简体   繁体   中英

How to create a custom hash inside form_tag block

I've got a Rails 3 app and I'm trying to create multiple db records from aa single form.

I've got a model, contents, which as attributes of body and id. I've got a view that displays a form that lists all records and puts a checkbox next to it (and sets the value to true/checked). A user has the option to un-select content records that they don't want.

<%= form_tag 'contents' do %>
  <% @contents.each do |content| %>
    <%= label_tag content.body %>
    <%= check_box_tag content.id, content.body, true %>
  <% end %>
  <br />
  <%= submit_tag "Next" %>
<% end %>

When this form pots, I get params that looks like this:

{"utf8"=>"✓",
 "authenticity_token"=>cooltoken",
 "1"=>"asdfasfdf",
 "2"=>"asdfasdf adf",
 "3"=>"asdf asdf asdf",
 "commit"=>"Next",
 "action"=>"create",
"controller"=>"contents"}

But what I want is a params hash that looks like this:

{"utf8"=>"✓",
 "authenticity_token"=>"cooltoken",
 'user_selections' => {
                      "1"=>"asdfasfdf",
                      "2"=>"asdfasdf adf",
                      "3"=>"asdf asdf asdf",
                     } 
"commit"=>"Next",
"action"=>"create",
"controller"=>"contents"}

How do I push the contents info into it's own hash (that I'm calling the 'user_selection' hash above)?

尝试这个:

<%= check_box_tag content.id, content.body, true, { name: "user_selections[#{content.id}]" } %>

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