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?
The easiest way might be to just split the query:
Based on your code it seems like
category_id
references only 1 category so I've changed it to singular.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.