associations - Silent failure in creating child record even with create! in Rails - expected behaviour or bug? -
i ran weird issue working code user creation stopped working without change in model or controller. have following relationship between user , company in user.rb:
has_many :company_users, dependent: :destroy has_many :companies, through: :company_users appropriate relationships defined in company.rb , company_user.rb files well. happens when user created, if haven't assigned company him, new company created , assigned him. obviously, means creating companyuser record associate them. done through before_create callback. this:
user = user.new(user_params) company = company.create(company_params) user.company_users.build(company: company) short version:
user saved, company saved, company_user not saved because failed validations. no errors raised create!. expected or bug in rails?
long version
this working fine until yesterday stopped working today. company , user created not through record, leaving records unassociated. like:
user.create! email: "mymail@gmail.com", password: "mypass" no errors raised, company , user created no association. after investigating time, found problem. in company_user.rb, there were:
validates_uniqueness_of :invitation_token validates_inclusion_of :invitation_status, in: invitation_statuses these columns added, meant records had nil values, , record nil wouldn't accepted. inclusion validation wouldn't accept nil. adding allow_blank: true both resolved issue.
the rails version 5.0.3 , ruby version 2.4.0. expected behaviour in rails, or bug? can avoid these kind of pitfalls in future - bit difficult handle errors when user.errors doesn't contain anything.
Comments
Post a Comment