验证特定操作的模型 [英] Validate model for certain action
问题描述
我只需要针对特定操作 (:create) 验证模型.我知道这不是一个好策略,但我只需要在我的情况下这样做.
I need to validate a model only for a certain action (:create). I know this is not a good tactic, but i just need to do this in my case.
我尝试使用类似的东西:
I tried using something like :
validate :check_gold, :if => :create
或
validate :check_gold, :on => :create
但是我遇到了错误.问题是我不能在编辑时执行我的自定义 check_gold 验证,而只能在创建时执行(因为必须在创建联盟时执行检查黄金,而不是编辑).
But i get errors. The problem is that i cannot have my custom check_gold validation execute on edit, but only on create (since checking gold has to be done, only when alliance is created, not edited).
感谢阅读:)
我正在附加一些实际代码:
I'm appending some actual code :
attr_accessor :required_gold, :has_alliance
validate :check_gold
validate :check_has_alliance
这是联盟模式.:required_gold 和 :has_alliance 都在控制器中设置(它们是虚拟属性,因为我需要来自控制器的信息).现在,实际的验证器是:
This is the Alliance model. :required_gold and :has_alliance are both set in the controller(they are virtual attributes, because i need info from the controller). Now, the actual validators are:
def check_gold
self.errors.add(:you_need, "100 gold to create your alliance!") if required_gold < GOLD_NEEDED_TO_CREATE_ALLIANCE
end
def check_has_alliance
self.errors.add(:you_already, "have an alliance and you cannot create another one !") if has_alliance == true
end
这非常适合创建,但我想将其限制为单独创建,而不是编辑或脚手架的其他操作.
This works great for create, but i want to restrict it to create alone and not edit or the other actions of the scaffold.
推荐答案
所有 ActiveRecord
验证器都有一个 :on
选项.
All ActiveRecord
validators have a :on
option.
validates_numericality_of :value, :on => :create
使用 validate_on_create
回调代替 validate
:
validate_on_create :check_gold
validate_on_create :check_has_alliance
如果您使用 validates_each
,您可以使用可用于验证器声明的标准选项.
If you use validates_each
you can use the standard options available for a validator declaration.
validates_each :required_gold, :has_alliance, :on => :create do |r, attr, value|
r.check_gold if attr == :required_gold
r.check_has_alliance if attr == :has_alliance
end
这篇关于验证特定操作的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!