如何重新加载我的索引页面

时间:2017-02-25 23:25:34

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

我的tutos索引中有这个过滤器:

 = simple_form_for :query, url: tutos_path, method: :get,  wrapper: :inline_form, html: {class: 'form-inline'} do |f|
        = f.input  :keyword, placeholder: "Keyword"
        = f.input  :category, collection: (Category.all.map {|c| c.name}) ,  prompt: "Select a category"
        = f.input  :user, collection: (User.order('nickname ASC').all.map {|u| u.nickname}), prompt: "Select a user"
        = f.button :submit, "Find", class:"btn btn-warning"
        = link_to t("search_form.best"),  best_voted_path, class: "btn btn-default"
        = link_to t("search_form.all"),  tutos_path, class: "btn btn-default"


        -if user_signed_in?
          = link_to t("search_form.create"), new_tuto_path, class:"btn btn-success"

过滤后,我无法通过link_to返回到我的tutos_path: 我有这个错误:

NoMethodError at /en/tutos
undefined method `[]' for nil:NilClass

在我的控制器中我有:

 def index
   @tutos = Tuto.all
   filter_tutos
  end

 def filter_tutos
   @tutos = Tuto.search(params[:query][:keyword]).includes(:user, :category) if params[:query][:keyword].present?
   @tutos = Tuto.joins(:user).where('users.nickname LIKE ?', params[:query][:user]) if params[:query][:user].present?
   @tutos = Tuto.joins(:category).where('categories.name LIKE ?', params[:query][:category]) if params[:query][:category].present?
 end

2 个答案:

答案 0 :(得分:0)

错误来自您的params[:query][:keyword].present?和其他类似错误,因为它被评估为params,然后是params [:query]。如果其中一个评估为nil,然后尝试运行nil[:query],因此[]未定义NilClass,则会返回错误。

您需要在函数中检查nil:

 def filter_tutos
   return if params[:query].nil? # Don't bother, if the query is nil
   @tutos = Tuto.search(params[:query][:keyword]).includes(:user, :category) if params[:query][:keyword].present?
   @tutos = Tuto.joins(:user).where('users.nickname LIKE ?', params[:query][:user]) if params[:query][:user].present?
   @tutos = Tuto.joins(:category).where('categories.name LIKE ?', params[:query][:category]) if params[:query][:category].present?
 end

据我记忆,params始终在Controller中设置。如果情况并非如此,那么您也需要调整您的零检查。

为了使它适合你自己的答案,并有一个后备方法,你可以这样做,检查是否

def index
  filter_tutos if params[:query].present?
  @tutos ||= Tuto.all
end

确保设置了@tutos。如果Tuto.all方法为零,则设置为filter_tutos

答案 1 :(得分:0)

我终于找到了......

在我的控制器中:

 def index
    if params[:query].present?
      filter_tutos
    else
      @tutos = Tuto.all
    end
  end
在我看来,

而不是我的= link_to t("search_form.all"), tutos_path, class: "btn btn-default"

我做了:

= link_to t("search_form.all"), {controller: 'tutos', action: 'index'}, class: "btn btn-success"