Question

I am trying to retrieve root category - subcategories by using Ancestry gem. I tried this in rails console it worked. It retrieved sub id's without problem, but when I am using in controller( actual application) it shows such error :

   Mysql2::Error: Operand should contain 1 column(s): SELECT COUNT(*) FROM `categories`  WHERE (id = 2,7,15,16)

Code in controller :

 @category = Category.find_by_name(params[:category])
 @sub_ids = @category.child_ids 
 @subcat = Category.where("id = ?", @sub_ids)  

Thanks (((((:

Was it helpful?

Solution

It's quite clear that the category with provided name doesn't exist (so Category.find_by_name method returns nil). You probably don't set @params instance variable properly.

About your second error, the last line in your code should be:

@subcat = Category.where(id: @sub_ids)

Or, to make it simpler, you could use existing library to handle this kind of logic, like acts_as_tree.

OTHER TIPS

Apparently Category.find_by_name(@params) returns nil so on the first line you're assigning nil to @category.

@category = Category.find_by_name(@params) # => nil

Then on the next line you're calling the #child_ids method on nil (ie. nil.child_ids) which of course is not defined.

Also, if @sub_ids is an array of IDs, in your last line you have to do:

@subcat = Category.where(id: @sub_ids)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top