Why doesn't updating this model trigger validations?
With Rails 3.1, I have:
class Status < ActiveRecord::Base
has_many :participations, :dependent => :destroy
has_many :users, :through => :participations
validates :users, :presence => true
end
In my unit test, I do:
user = User.create(:name => "Bob")
status1 = Status.create(:description => "available")
user.statuses << status1
and get:
ActiveRecord::RecordInvalid: Validation failed: users can't be blank
but, if instead of the last line I do:
status1.users << user
it works fine.
Why does the validation get triggered for:
user.statuses << status1
UPDATE:
the test in full
test "Return all statuses associated with the manager" do
manager = Manager.create(:email => "foo@bar.com", :password => "password", :password_confirmation => "password")
workshop = Workshop.create(:name => "Bob Autos")
manager.workshop = workshop
manager.save
user = User.create(:name => "a customer")
workshop.users << user
sta开发者_运维知识库tus1 = Status.create(:description => "Car is ready")
status2 = Status.create(:description => "problem with exhaust")
status3 = Status.create(:description => "parts delivered")
user.statuses << status1
user.statuses << status2
assert_equal([status1, status2], manager.statuses)
user.statuses << status3
assert_equal([status1, status2, status3], manager.statuses)
end
The validation is on Status
, not on User
. A model's validation is only triggered when that model is updated, and you didn't actually update the User
model (since statuses
is an association, not a field).
If you want validation on one object to trigger validation on another, you should use validates_associated
:
class Status
validates_associated :users
end
(On a related note, though, why does a Status have many users? Seems like a Status should only be on one user.)
Because the status1.users
collection isn't automatically updated when you do user.statuses << status1
精彩评论