Search code examples
ruby-on-railsrubycheckboxruby-on-rails-2

Issue keeping checkbox selection


I did a checkbox array but the options that I select are not keeping the check after submit.

Here is the table:

|people|
  |id|  |name|
    1    Bill
    2    Steve
    3    Mark
    4    MrYoshi

Here is the controller:

def searching
  @people = Person.all
  @search = Person.find(:all,:conditions=>['id IN (?)',params[:search_id] ])
end

Here is the view:

<% form_tag :controller=>"person",:action=>"searching" do %>
  <% @people.each do |c| %>
    <%= check_box_tag "search_id_#{c.id}",  c.id.to_s ,params[:search_business].to_s == c.id.to_s %>
  <% end %>
 <%= submit_tag "SEARCHING" %>
<% end %>

I read this information http://apidock.com/rails/ActionView/Helpers/FormTagHelper/check_box_tag

Here is a checkbox example working but is not using arrays values:

<%= check_box_tag "example", "2", params[:example].to_s == "2", {:multiple => true}  %>

I tried this line, parameters are sending but is not keeping the checkbox selected:

<%= check_box_tag "search_id[]",  c.id.to_s ,params[:search_business].to_s == c.id.to_s %>
###Parameters: { "commit"=>"SEARCHING", "search_id"=>["1","2"]

I tried this line, parameters are sending but is not keeping the checkbox selected:

<%= check_box_tag "search_id[]",  c.id.to_a ,params[:search_business].to_a == c.id.to_a %>
###Parameters: { "commit"=>"SEARCHING", "search_id"=>["1","2"]

I tried this line, parameters are sending but is not keeping the checkbox selected:

<%= check_box_tag "search_id[]",  c.id.to_a %>
###Parameters: { "commit"=>"SEARCHING", "search_id"=>["1","2"]

I tried this line, parameters are sending but is not keeping the checkbox selected:

<%= check_box_tag "search_id[]",  c.id %>
###Parameters: { "commit"=>"SEARCHING", "search_id"=>["1","2"]

Please somebody can help me with this example?

I will really appreciate all kind of help.


Solution

  • For checkboxes, you should send the params through in an array. This is done by appending "[]" to the "name" attribute of the input, like you've done in some of your attempts. I would do this like so:

    controller (same action called before search and by the search form)

    @people = Person.all
    if params[:search_ids]
      @search = Person.find_all_by_id(params[:search_ids])
    end
    

    view

    <% form_tag :controller=>"person",:action=>"searching" do %>
      <% @people.each do |c| %>
        <% checked = @search && @search.collect(&:id).include?(c.id) %>
        <%= check_box_tag "search_ids[]", c.id, checked %>
      <% end %>
     <%= submit_tag "SEARCHING" %>
    <% end %>
    

    EDIT - i just realised i mixed up @people (which is all people in the db) and @search which should just be the checked people.