I’m having a problem with a check_box_tag that I am using when trying to search for archived projects in a table.
<%= hidden_field :archive, :value => false %>
<% if current_user.try(:admin?) %>
Archive: <%= check_box_tag :archive, true, false, :class => "archive" %></H2>
<% else %>
<%= hidden_field :archive, :value => false %>
<% end %>
So if the user isn’t an admin, archive is always false.
If the user is an admin, then archive is always false, unless they check the checkbox.
When the check box is checked, and a search is submitted, the results are shown, but the box becomes unchecked again. Is there a way to check it checked? I tried using :selection => params[:archive] but that didn’t seem to work. Thanks in advance.
Adding search function
def self.like(text); "%#{text}%"; end
def self.search(search_archive, search_client)
_projects = Project.scoped
if search_archive.present?
_projects = _projects.where(:archive => search_archive)
end
if search_client.present?
_projects = _projects.where ['client LIKE ?', like(search_client)]
end
_projects
end
end
Search action:
def search
@search = params[:archive], params[:client]
@project_search = Project.search(*@search).order(sort_column + ' ' + sort_direction).paginated_for_index(per_page, page)
@search_performed = !@search.reject! { |c| c.blank? }.empty?
@project = Project.new(params[:project])
respond_to do |format|
format.html # search.html.erb
format.json { render :json => @project }
end
end
URLS:
When I search for Client: Test, which archived checked:
http://localhost:3000/search?utf8=%E2%9C%93&%5Bclient%5D=Test&%5D=&archive=true&per_page=10
No projects are found which is correct, now I unclick archived:
http://localhost:3000/search?utf8=%E2%9C%93&%5Bclient%5D=Test&%5D=&archive%5B%7B%3Avalue%3D%3Efalse%7D%5D=&per_page=10
Which again shows the correct results, but the box is now checked, but should be unchecked, incase I want to refine the search
Fix:
In my search function:
if search_archive.present?
_projects = _projects.where(:archive => search_archive == "true")
end
if !search_archive.present?
_projects = _projects.where(:archive => search_archive == "false")
end
In my search view:
<% if current_user.try(:admin?) %>
Archive: <%= check_box_tag :archive, true, !!params[:archive], :class => "archive" %></H2>
<% end %>
Change
To
Ref
check_box_tagfor more information