문제

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
도움이 되었습니까?

해결책

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.

다른 팁

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top