问题
An Organization model has a 1:many association with a User model. I have the following validation in my User model file:
belongs_to :organization
validates_presence_of :organization_id, :unless => 'usertype==1'
If usertype is 1, it means the user will have no organization associated to it. For a different usertype the presence of an organization_id should be mandatory.
The organization model includes:
has_many :users
accepts_nested_attributes_for :users, :reject_if => :all_blank, :allow_destroy => true
My seeds file uses nesting and includes:
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"])
On seeding this generates the error below. Removing the validation from the model solves it, but I don't want to do that. How can I solve this?
Validation failed: Users organization can't be blank
回答1:
Found this : Validating nested association in Rails (last chapter)
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
The documentation is not quite clear about it but I think it's worth a try. see this comment, stating that the association lookout will use the objects in memory and not fetch them from the database, which would be what you need.
EDIT
removed inverse_of on the Organization class.
回答2:
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
When calling Organization.create! with nested attributes, rails first creates the Organization without any validations, then it builds the User, performs all validations on it, then saves it to database if all is green, just as calling create without the bang.
来源:https://stackoverflow.com/questions/30993850/seeding-fails-validation-for-nested-tables-validates-presence-of