开发者

activerecord validation - validates_associated

I'm unclear on what this method actually does or when to use it.

Lets say I have these models:

Person < ...
  # id, name
  has_many :phone_numbers
end

PhoneNumber < ...
  # id, number
  belongs_to :person
  validates_length_of :number, :in => 9..12    
end

When I create phone numbers for a person like this:

@person = Person.find(1)
@person.phone_numbers.build(:number => "123456")
@person.phone_numbers.build(:number => "12346789012")
@person.save

The save fails because the first number wasn't valid. This is a good thing, to me. But what I don't understan开发者_开发百科d is if its already validating the associated records what is the function validates_associated?


You can do has_many :phone_numbers, validate: false and the validation you're seeing wouldn't happen.

Why use validates_associated then? You might want to do validates_associated :phone_numbers, on: :create and skip validation on update (e.g. if there was already bad data in your db and you didn't want to hassle existing users about it).

There are other scenarios. has_one according to docs is validate: false by default. So you need validates_associated to change that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜