【发布时间】:2015-03-07 19:59:40
【问题描述】:
class Recipe < ActiveRecord::Base
def self.tagged_with(name)
recipes = Tag.find_by(name: name).recipes
end
end
在控制器中
def tag
@recipes = Recipe.tagged_with(params[:tag])
render 'index'
end
路线
get 'tag/:tag', to "recipes#tag"
我怎样才能保护这个方法不被破坏?如果我搜索一个尚未创建的标签,我会得到一个 noMethodError 'recipes' for nil:NilClass。我试过放
return false if recipes.nil?
还有
redirect_to(recipes_path) if recipes.nil?
在方法结束时,但没有任何效果。
【问题讨论】:
-
if recipes && recipes.nil?
标签: ruby-on-rails ruby tagging