You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails分类搜索报错Couldn't find all Post with 'id': (false, true) 求助

报错原因

你的代码存在两个核心错误:

  1. 字段引用逻辑错误:pluck(:@category)中的:@category是字面量符号,并不会解析@category变量的值作为字段名;即使去掉冒号写pluck(@category),逻辑也完全错误——pluck会直接取出该分类字段的所有值(也就是true/false布尔值),而不是你需要的post_id。
  2. 缺少筛选步骤:你没有先筛选对应分类字段为true的PostCategory记录,直接把取出的布尔值传给Post.find,自然会出现要查找id为false/true的报错。

正确实现方案

1. 修正控制器代码

def category
  @category = params[:category_name].to_s
  # 白名单校验,避免非法参数导致SQL注入
  valid_categories = %w[casual natural clean rock formal street hip_hop sports outdoors surf]
  unless valid_categories.include?(@category)
    # 非法分类处理逻辑可根据业务调整,这里示例跳回首页加提示
    redirect_to root_path, alert: "请求的分类不存在" and return
  end

  # 步骤1:筛选对应分类为true的PostCategory记录,取出关联的post_id
  post_ids = PostCategory.where("#{@category} = ?", true).pluck(:post_id)
  # 步骤2:根据post_id查询Post记录,用where避免找不到记录时报错
  @posts = Post.where(id: post_ids)
end

2. 性能优化方案(可选)

如果你的Post模型已经正确配置了has_one :post_category关联,可以用关联查询减少SQL查询次数,性能更优:

# 替换上面的两行查询代码即可
@posts = Post.joins(:post_category).where("post_categories.#{@category} = ?", true)

3. 额外优化建议

你的视图链接建议用Rails路由助手生成,避免硬编码路径出错,先给路由加别名:

# 路由配置修改为
get '/category/:category_name', to: 'pages#category', as: :category

视图中的链接就可以替换为:

<li><%= link_to 'casual', category_path('casual') %></li>
<!-- 其余分类按相同格式替换即可 -->

后续修改路由路径时无需批量调整视图代码,可维护性更强。

注意:你给出的模型关联写反了,正确写法是Post模型中定义has_one :post_category,PostCategory模型中定义belongs_to :post,关联关系写反会导致关联查询报错。


内容的提问来源于stack exchange,提问作者dxo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 07:36:03