1
我想验证一个字段取决于相关模型的属性。看代码会更有意义(我希望)反向validates_associated
class User < ActiveRecord::Base
has_and_belongs_to_many :user_groups
has_one :profile, :dependent => :destroy
accepts_nested_attributes_for :profile
validates_associated \
:profile,
:allow_destroy => true
end
class Profile < ActiveRecord::Base
belongs_to :user
validates_presence_of \
:business_name,
:if => self.user.user_groups.first.name == 'Client'
end
当我提交表单,以创建一个新用户,我得到
undefined method `user_groups' for nil:NilClass
基本上我只是想验证字段的存在business_name如果我正在创建一个新的客户端。
我也使用
:if => Proc.new { |p| p.user.user_groups.first.name == 'Clients' }
具有相同的结果尝试。
也许我正在吠叫完全错误的树,但任何建议,以完成此?
嗯......这是不可能的,然后直到validates_associated可以接受参数? – brewster 2010-07-17 03:21:48
你的逻辑在这里很复杂。我更新了我的原始答案,以显示如何将配置文件中的验证逻辑与独立分离。你需要在is_business传递国旗以触发档案建立特殊业务validatoins。 – Winfield 2010-07-17 17:29:35