为什么不更新此模型触发验证?

时间:2011-07-27 11:40:38

标签: ruby-on-rails ruby-on-rails-3 unit-testing validation

使用Rails 3.1,我有:

class Status < ActiveRecord::Base
  has_many :participations, :dependent => :destroy
  has_many :users, :through => :participations

  validates :users, :presence => true
end

在我的单元测试中,我这样做:

user = User.create(:name => "Bob")
status1 = Status.create(:description => "available")
user.statuses << status1

并获得:

  

ActiveRecord :: RecordInvalid:验证失败:用户不能为空

但是,如果不是我做的最后一行:

status1.users << user

它工作正常。

为什么验证会被触发:

user.statuses << status1

更新:

完整的测试

 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

    status1 = 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

2 个答案:

答案 0 :(得分:2)

验证位于Status,而不是User。模型的验证仅在更新该模型时触发,并且您实际上并未更新User模型(因为statuses是关联,而不是字段)。

如果要对一个对象进行验证以触发另一个对象的验证,则应使用validates_associated

class Status
  validates_associated :users
end

(但是,在相关的说明中,为什么状态有很多用户?看起来状态应该只有一个用户。)

答案 1 :(得分:1)

因为执行status1.users

user.statuses << status1集合未自动更新