Ruby on Rails: where returning nil

2019-08-10 08:11发布

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}%")

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?

2条回答
狗以群分
2楼-- · 2019-08-10 09:02

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}%")

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

查看更多
三岁会撩人
3楼-- · 2019-08-10 09:08

You should look into doing an OUTER JOIN against the items table which will give you categories regardless of whether or not their items meet the name filter.

查看更多
登录 后发表回答