我正在尝试将传递给搜索参数的字符串传递给搜索范围。
但是,我无法找到一种方法来检测搜索中是否包含特定属性。下面的代码有效但如果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
答案 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 %>