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

Checkbox is cleaning after searching


I did an application using checkbox options but after doing click on search is cleaning what checked and starting all checked (is not saving the last checked clicked).

Here the table

|people|
  |id|    |name|   |state|
   1       ABC       0
   2       DEF       0  
   3       DEF       1
   4       DEF       1

Here the controller:

class PersonController < ApplicationController

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

end

Here is the view:

 <% form_tag :controller=>"person",:action=>"search" do %>
    Single  <%= check_box_tag "state", "0", params[:state] %>
    Married <%= check_box_tag "state", "1", params[:state] %>
    <%= submit_tag "Search", :name => nil %>
 <% end %>

 <% @people.each do |p|  %>
    p.name
    p.state
 <% end %>

I tried:

    Single  <%= check_box_tag "state", "0", params[:state].to_i %>
    Married <%= check_box_tag "state", "1", params[:state].to_i %>

And tried this too:

    Single  <%= check_box_tag "state", 0, params[:state].to_i %>
    Married <%= check_box_tag "state", 1, params[:state].to_i %>

And finally this:

    Single  <%= check_box_tag "state", "0", params[:state] %>
    Married <%= check_box_tag "state", "1", params[:state] %>

Everytime do click on SEARCH, the check option is cleaning and isn't saving the checked that I did.

The checkbox isn't saving what I checked after doing SEARCH.

Please somebody can help me?


Solution

  • Syntax for checkbox tag is

    check_box_tag(name, value = "1", checked = false, options = {})
    

    So in third parameter you have to pass either true or false, depending on your params to check or uncheck the checkbox.

    Try this

    Single  <%= check_box_tag "state", "0", params[:state].to_s == '0' %>
    Married <%= check_box_tag "state", "1", params[:state].to_s == '1' %>