Ruby on Rails:返回零的地方 [英] Ruby on Rails: where returning nil

查看:77
本文介绍了Ruby on Rails:返回零的地方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,我获得了某个类别,并且根据其名称过滤了相关项目. 下面的代码应该很清楚:

In my app I'm obtaining a certain category, and I'm filtering the associated items based on their name. The following code should be pretty clear:

categories = Category.where(:id => params[:category_id]).includes(:items).where("lower(items.name) like ?", "%#{params[:keywords].downcase}%")

但是,如果名称过滤器排除了所有项目,则where返回的categories对象为nil.这是预期的行为吗?即使项目不存在,如何获取类别?

However, if the name filter excludes all the items, the categories object returned by where is nil. Is this the expected behaviour? How can I get the category even either items exist or not?

推荐答案

最简单的方法可能就是拆分查询:

The easiest way might be to just split the query:

@category = Category.find(params[:category_id])
@items = @category.items.where("lower(items.name) like ?", "%#{params[:keywords].downcase}%")

根据您的代码,似乎category_id仅引用1个类别,因此我将其更改为单数.

Based on your code it seems like category_id references only 1 category so I've changed it to singular.

这篇关于Ruby on Rails:返回零的地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆