[英]Validations with accept_nested_attributes_for
I'm having issues with some code of my rails app, imagine the follow scenario: 我的rails应用程序的某些代码有问题,请设想以下情形:
user.rb user.rb
class User < ActiveRecord::Base
has_one :participant, dependent: :destroy
validates_presence_of :username
accepts_nested_attributes_for :participant
end
participant.rb participant.rb
class Participant < ActiveRecord::Base
belongs_to :user
validates_presence_of :phone_number
end
The problem happens when I run valid?
运行
valid?
时会发生问题valid?
method 方法
user = User.first
user.valid?
#=> true
At this point user validations are ok (it's running only the validations from User model), but if for some reason the association with participant is loaded, then valid?
此时,用户验证就可以了(它仅运行来自User模型的验证),但是如果由于某种原因加载了与参与者的关联,那么
valid?
method's gonna run the validations from User and from Participant which IMHO is wrong since user
is an instance of User model 方法将运行来自用户和参与者的验证,因为
user
是用户模型的实例,因此恕我直言是错误的
user.participant
Participant Load (0.3ms) SELECT "participants".* FROM "participants" WHERE "participants"."user_id" = ? LIMIT 1 [["user_id", 1]]
=> #<Participant id: 1, user_id: 1, phone_number: "", created_at: "2015-01-13 18:15:34", updated_at: "2015-01-13 18:48:27">
user.valid?
#=>false
user.errors.full_messages
#=> ["Participant phone number can't be blank"]
I would agree with this validation if I were updating something in participant model but I'm not. 如果我要更新参与者模型中的某些内容,我会同意这种验证,但我不是。 Is this a bug or there is any way that I could skip the associated validations?
这是一个错误还是有什么办法可以跳过相关的验证?
Thanks 谢谢
In Rails nested attributes pass behavior to the parents children. 在Rails中,嵌套属性将行为传递给父级子级。 So if you call .valid?
那么, 如果您致电.valid? on the parent it will check validations on all the children .
在父母身上,它会检查所有子女的身分 。 This is the intended structure and is this way to ensure that the associated model is valid, because you asked it to be.
这是预期的结构,通过这种方式可以确保关联的模型有效,因为您要求它是有效的。
The question I have for you is why would you have a validation on your Participant model for the phone_number attribute if you want to skip that validation? 我要问的问题是,如果要跳过该验证,为什么要在参与者模型中对phone_number属性进行验证? You either need to remove the validation for phone_number or ensure that a phone_number is present.
您或者需要删除对phone_number的验证,或者确保存在phone_number。 I think you need to re-assess the structure of your model's and validations with this in mind.
我认为您需要考虑到这一点重新评估模型的结构和验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.