嵌套表的播种验证失败 (validates_presence_of)

Seeding fails validation for nested tables (validates_presence_of)

组织模型与用户模型有 1:many 关联。 我的用户模型文件中有以下验证:

belongs_to :organization
validates_presence_of :organization_id, :unless => 'usertype==1'

如果 usertype 为 1,则表示用户没有关联的组织。对于不同的用户类型,organization_id 的存在应该是强制性的。

组织模型包括:

has_many :users
accepts_nested_attributes_for :users, :reject_if => :all_blank, :allow_destroy => true

我的种子文件使用嵌套并包含:

Organization.create!(name: "Fictious business",
                     address: Faker::Address.street_address,
                     city: Faker::Address.city,
  users_attributes: [email: "helpst@example.com",
                     username: "helpyzghtst", 
                     usertype: 2,
                     password: "foobar", 
                     password_confirmation: "foobar"])

播种时会产生以下错误。从模型中删除验证可以解决它,但我不想这样做。我该如何解决这个问题?

Validation failed: Users organization can't be blank

organization = Organization.create! name: "Fictious business",
                                    address: Faker::Address.street_address,
                                    city: Faker::Address.city

User.create! email: "helpst@example.com",
             username: "helpyzghtst", 
             usertype: 2,
             password: "foobar", 
             password_confirmation: "foobar"
             organization: organization

更新

使用嵌套属性调用 Organization.create! 时,rails 首先创建 Organization 而不进行任何验证,然后 构建 User,对其执行所有验证,然后将其保存到数据库(如果全部为绿色),就像调用 create 时没有爆炸一样。

找到这个:Validating nested association in Rails(最后一章)

class User
  belongs_to :organization, inverse_of: :users
  validates_presence_of :organization_id, :unless => 'usertype==1'
end

class Organization
  has_many :users
  accepts_nested_attributes_for :users, :reject_if => :all_blank, :allow_destroy => true
end

文档对此不是很清楚,但我认为值得一试。看到这个 comment,声明关联监视将使用内存中的对象而不是从数据库中获取它们,这正是您需要的。

编辑

在组织 class 上删除了 inverse_of。