0

It seems Rails will only validate an existing invalid nested model if the nested model's attributes have changed.

With the following models:

class Person < ActiveRecord::Base
  has_many :addresses
  accepts_nested_attributes_for :addresses
end

class Address < ActiveRecord::Base
  belongs_to :person
  validates_presence_of :street
end

The following code for example, will save and return true:

p = Person.first
p.update_attributes({:first_name => "Bryan", :addresses_attributes=>{"0"=>{:street=>"", :id => 1}})

Is there a way to validate the nested model as if it's attributes have changed? ( while retaining errors )

1
  • 1
    Use the save or save! methods. update_attributes is for special cases, and (I would have to look but) think it doesn't trigger certain checks that the straight-up save methods do. Commented Mar 27, 2012 at 2:01

1 Answer 1

1

It works for me -- here's a test-case I created to prove it

require 'test_helper'

class PersonTest < ActiveSupport::TestCase

  test "update address" do
    expected_new_address="pandascout"
    person = Person.create(name: "jwo")
    address = person.addresses.create(street: "123 Elm")

    person.update_attributes({:addresses_attributes=>{"0"=>{:street=>expected_new_address, :id=>address.id}}})
    assert_equal expected_new_address, person.addresses.first.street
  end
end

The only thing I can think of is you have a reference to "address" and you need to reload it.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for taking the time to answer and create this test.
@deadkarma sure -- I was curious and this was a way we could both reproduce the results... Did you find what you were looking for with this question? If so, please mark as accepted -- if not, let me know and I can dive further into.
I created a fresh new app, and it validates the nested model just fine. I reverted to a much earlier commit in my app, and it worked there as well. So it must be some change between now and 6 months ago :/
I think I found the crux of the problem. If the nested model hasn't changed? it doesn't run validations on it, thus allowing the parent model to update without errors. In your test-case, you are updating the street attribute on a valid address model.
So you want to run validations against a model that didn't change?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.