Reputation: 651
I want my user to select out of a pre-filtered list of model instances.
Let's say @pages
is an ActiveRecord Relationship of multiple pages.
Then in my view I want to display a form where the user can select them:
[X] Page One
[ ] Page Two
[ ] Page Three
And in my next controller action to be the params something like
selection => [12345 => true, 23456 => false, 56788 => false]
Where the numbers are the ids. Or even better the instances themselves.
The only thing I can figure out is
<%= form_with url: validate_pages_path do |form| %>
<% Page.all.each do |page| %>
<%= check_box_tag page.id %>
<%= label_tag page.name %>
<% end %>
<%= form.submit %>
<% end %>
But then I end up with a params mess like
{"utf8"=>"✓", "authenticity_token"=>"...", "992936610"=>"1", "992936644"=>"1", "commit"=>"Save "}
I don't have a model that nests pages
that is definitely making it quite tricky
Upvotes: 3
Views: 287
Reputation: 54882
As I suggested in my comment, here the code in your case:
<%= form_with url: validate_pages_path do |form| %>
<% Page.all.each do |page| %>
# new stuff below
<%= hidden_field_tag "pages[#{page.id}]", false %>
<%= check_box_tag "pages[#{page.id}]", true %>
# /new stuff above
<%= label_tag page.name %>
<% end %>
<%= form.submit %>
<% end %>
As you can see, we used the name "pages[page.id]"
, so you should end up having params[:pages]
which wraps the whole thing.
Upvotes: 3