Seeding fails validation for nested tables (validates_presence_of)

帅比萌擦擦* 提交于 2020-01-16 02:52:26

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!