播种未通过嵌套表validation(validates_presence_of)
组织模型与用户模型具有1:多的关联。 我的用户模型文件中有以下validation:
belongs_to :organization validates_presence_of :organization_id, :unless => 'usertype==1'
如果usertype为1,则表示用户没有与之关联的组织。 对于不同的usertype,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解决了它,但我不想这样做。 我怎么解决这个问题?
validation失败:用户组织不能为空
发现这个: validationRails中的嵌套关联 (最后一章)
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
文档不是很清楚,但我认为值得一试。 请参阅此注释 ,声明关联了望将使用内存中的对象而不是从数据库中获取它们,这将是您所需要的。
编辑
删除了Organization类的inverse_of。
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
UPDATE
在调用Organization.create!
对于嵌套属性,rails首先创建没有任何validation的Organization
,然后构建 User
,对其执行所有validation,然后将其保存到数据库(如果全部为绿色),就像调用没有爆炸的create
。