使用Ransack Gem时同模型其他查询报错的问题排查求助
解决Ransack查询后@roasts为nil的问题
兄弟,你这个错误的根源太明显了——当提交搜索请求进入if params[:q]分支时,你只给@roastsalpha赋了值,完全没管视图里用到的@roasts变量!这就导致搜索后@roasts是nil,视图调用@roasts.count自然就报错了。
而且还有个隐形问题:你代码最后一行不管有没有搜索,都把@roastsalpha重新赋值成所有烘焙记录的排序结果,这等于直接把Ransack的搜索结果覆盖了,完全白搜了啊!
给你改好的控制器代码,直接用就行:
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]) @roasts = @q.result # 关键:给@roasts赋值搜索结果 @roastsalpha = @roasts.order(:name) # 基于搜索结果做字母排序 else @roasts = Roast.all @roastsalpha = Roast.order(:name) end # 额外优化:@roastsdesc也用@roasts来排序,这样搜索后最新列表也是结果子集 @roastsdesc = @roasts.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 end
简单说下修改逻辑:
- 不管有没有搜索参数,
@roasts都会被赋值,视图里的@roasts.count就能正常工作了 - 搜索后的
@roastsalpha是基于搜索结果排序,不会被后面的代码覆盖 - 把
@roastsdesc改成基于@roasts排序,这样搜索后展示的最新记录也是搜索结果里的,逻辑更合理
内容的提问来源于stack exchange,提问作者Simon Cooper
相关产品推荐
相关产品推荐

