ROR + Ransack:渲染选定的搜索参数

时间:2017-10-13 16:59:09

标签: ruby-on-rails ruby-on-rails-5 ransack

我正在尝试将传递给搜索参数的字符串传递给搜索范围。

但是,我无法找到一种方法来检测搜索中是否包含特定属性。下面的代码有效但如果param为空则不会隐藏按钮。

物品/ browse.html.erb

  <% if params[:q].present? == true %>
    <button type="button" class="btn btn-outline-primary btn-lg"><%= params[:q][:title_cont] %></button>
    <button type="button" class="btn btn-outline-primary btn-lg"><%= params[:q][:categories_name_cont] %></button>
    <button type="button" class="btn btn-outline-primary btn-lg"><%= params[:q][:user_name_cont] %></button>
  <% end %>

我尝试使用以下条件,但却出现此错误:undefined method [] for nil:NilClass

 <% if params[:q][:title_cont].present? == true %>

文章控制器

  def browse
    @q = Article.ransack(params[:q])
    @articles = @q.result.includes(:categories, :users)
  end

1 个答案:

答案 0 :(得分:1)

我通过更改<% if params[:q][:title_cont].present? == true %>

来修复它

<% if @q.title_cont.present? == true %>

browse.html.erb

    <% if @q.title_cont.present? == true %>
      <button type="button" class="btn btn-outline-primary btn-lg"><%= params[:q][:title_cont] %></button>
    <% end %>
    <% if @q.categories_name_cont.present? == true %>
      <button type="button" class="btn btn-outline-primary btn-lg"><%= params[:q][:categories_name_cont] %></button>
    <% end %>
    <% if @q.user_name_cont.present? == true %>
      <button type="button" class="btn btn-outline-primary btn-lg"><%= params[:q][:user_name_cont] %></button>
    <% end %>