在任何字符串属性(Photo [:title],User [:name]等)中,有一些单词永远不会显示在我的webapp上。以下代码适用于我的控制器:
PhotosController
def create
@photo = current_user.photos.build(photo_params)
if @photo.title.include? "foo"
@photo = nil
flash[:warning] = "Photo failed!, restricted words"
redirect_to new_photo_path
else
if @photo.save
flash[:success] = "Photo created!"
redirect_to new_photo_path
else
flash[:warning] = "Photo failed!"
redirect_to new_photo_path
end
end
end
显然,我不想在控制器中为每个字符串属性无休止地重复自己。我需要创建一个方法,可以放在application.rb中,并在我的所有控制器中使用。
答案 0 :(得分:1)
class Photo
validate :title_with_foo
def title_with_foo
errors.add(:base, 'Photo failed!, restricted word') unless title.include? "foo"
end
end
添加如上所述的模型级验证