Question

I have some category tree constructed using Ancestry gem for Rails 3 I am able to use all Ancestry methods between console and other controllers. But now I am facing problem to use methods like root? and is_root? To determinate if the selected cat is root category.

My code inside Application controller

private
def set_categories
  def set_ids
    case action_name
    when "index"

   @origin_cat = Category.find_by_name(params[:category])

    if @origin_cat.root?
    @descendant_ids = @origin_cat.descendant_ids
    @descendant_prods = Product.where(:category_id => @descendant_ids  ).paginate(:per_page=>10, :page=> params[:page])
else

    end

......

My erorr looks like this :

undefined method `root?' for nil:NilClass
Was it helpful?

Solution

You should first check whether @origin_cat is not nil, than whether @origin_cat.root? is true or not, as following:

   @origin_cat = Category.find_by_name(params[:category])

  if @origin_cat && @origin_cat.root?
    @descendant_ids = @origin_cat.descendant_ids
    @descendant_prods = Product.where(:category_id => @descendant_ids  ).paginate(:per_page=>10, :page=> params[:page])
  else

  end

or you can just do:

  if @origin_cat.try(:root?)

With try, even if @origin_cat is nil, it will just return nil, instead of throwing an error.

More details on try here.

OTHER TIPS

Your @origin_cat is nil.Make sure the value of params[:category] is not nil

if @origin_cat.present? && @origin_cat.root?
    @descendant_ids = @origin_cat.descendant_ids
    @descendant_prods = Product.where(:category_id => @descendant_ids).paginate(:per_page=>10, :page=> params[:page])
else

end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top