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.