Ruby on Rails:check_box_tag没有保存状态

时间:2012-10-17 15:03:20

标签: ruby-on-rails ruby search checkbox

我在尝试在表格中搜索已归档项目时遇到check_box_tag问题。

<%= 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 %>

因此,如果用户不是管理员,则存档始终为false。

如果用户是管理员,则归档始终为false,除非他们选中该复选框。

选中复选框并提交搜索后,将显示结果,但该框将再次取消选中。有没有办法检查它?我尝试使用:selection => params[:archive],但似乎没有用。提前谢谢。

添加搜索功能

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

搜索操作:

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:

当我搜索已归档的客户:测试时:

http://localhost:3000/search?utf8=%E2%9C%93&%5Bclient%5D=Test&%5D=&archive=true&per_page=10

没有找到正确的项目,现在我取消了存档:

http://localhost:3000/search?utf8=%E2%9C%93&%5Bclient%5D=Test&%5D=&archive%5B%7B%3Avalue%3D%3Efalse%7D%5D=&per_page=10

再次显示正确的结果,但现在已选中该框,但应取消选中,此时我想优化搜索

修正: 在我的搜索功能中:

if search_archive.present?
  _projects = _projects.where(:archive => search_archive == "true")
end
if !search_archive.present? 
  _projects = _projects.where(:archive => search_archive == "false")
end

在我的搜索视图中:

<% if current_user.try(:admin?) %>
  Archive: <%= check_box_tag :archive, true, !!params[:archive], :class => "archive" %></H2>

<% end %>

1 个答案:

答案 0 :(得分:2)

更改

<%= check_box_tag :archive, true, false, :class => "archive" %>

<%= check_box_tag :archive, true, !!params[:archive], :class => "archive" %>

参考check_box_tag了解更多信息