如何在 Rails 中单独跳过特定控制器上的 before_create
example
class User < ActiveRecord::Base
before_create :validate_email
def validate_email
----
end
end
我希望仅在此控制器上跳过此操作,
class FriendsController < ApplicationController
def new
end
def create
end
end
这是一个 hack,但您可以向模型类添加一个虚拟属性,该属性只是充当一个标志来指示回调是否应该运行。然后控制器操作可以设置标志。就像是:
class User < ActiveRecord::Base
before_create :validate_email, :unless => :skip_validation
attr_accessor :skip_validation
def validate_email
...
end
end
class FriendsController < ApplicationController
def create
@user = User.find # etc...
@user.skip_validation = true
@user.save
end
end
我不确定是否before_create
回调的:unless
选项可以直接引用虚拟属性的名称。如果不能,那么您可以将其设置为模型中方法名称的符号,然后简单地让该方法返回skip_validation
属性的值。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)