Ransack导致模型上的其他查询出现问题

时间:2018-01-31 09:20:46

标签: ruby-on-rails ransack

我正在尝试实施Ransack gem。我认为我有宝石工作,但我的问题是在同一模型上的其他查询。例如,我在索引页面上的烤肉总数上有一个简单的<%= @roasts.count %>。但是当我提交搜索查询(undefined method 'count' for nil:NilClass)时,我收到错误http://localhost:3000/roasts?utf8=%E2%9C%93&q%5Bname_cont%5D=firefox&commit=Search。我90%肯定这是因为我在if-else语句下设置了查询,但我无法确定正确的设置。

控制器/ roast_controller.rb

class RoastsController < ApplicationController
  before_action :set_roast, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, only: [:create, :edit, :update, :destroy]
  before_action :set_search

  def index
    if params[:q]
      @q = Roast.ransack(params[:q])
      @roastsalpha = @q.result.order(:name)
    else
      @roasts = Roast.all
    end
      @roastsalpha = Roast.order(:name)
      @roastsdesc = Roast.all.order("created_at DESC")
      @mostpopularroast = Roast.group(:country).select(:country).order("count(*) desc").first
      @mostpopularblend = Roast.group(:bestfor).select(:bestfor).order("count(*) DESC").first
      @countroastschart = Roast.order("roaster DESC").all
  end

1 个答案:

答案 0 :(得分:1)

看一下你的指数行动:

def index
    if params[:q]
      @q = Roast.ransack(params[:q])
      @roastsalpha = @q.result.order(:name)
    else
      @roasts = Roast.all
    end

您收到错误是因为@roasts为零。如果我在假设您的set_search操作正在执行类似@search = Roast.ransack(params[:q])的操作时表示正确,则会在每个操作和设置params[:q]之前调用此操作。所以如果我们看看你的if语句; params[:q]永远是真的,永远不会设置@roasts。我认为要解决这个问题,你应该删除if-else语句。