In my ruby on rails application I have a problem while I'm trying to save a model after cloning it. I have the following models.
class Company < ApplicationRecord
has_many :employees
end
class Employee < ApplicationRecord
belongs_to :company
has_one :user
end
class User < ApplicationRecord
belongs_to :employee
end
When I user the following piece of code I get 'ActiveRecord::RecordInvalid: Validation failed: Employee must exist' error.
company = Company.new
employee = Employee.new(company: company)
user = User.new(name: 'John',email: 'example@gmail.com',password: 'password')
user.employee = employee
u = user.dup
u.save!
On the other hand, when I use 'clone' instead of 'dup' Rails tries to save User model twice and this leads exception
company = Company.new
employee = Employee.new(company: company)
user = User.new(name: 'John',email: 'example@gmail.com',password: 'password')
user.employee = employee
u = user.clone
u.save!
If I save model without dupping and cloning, there is no problem. In my application I'm using builder pattern and have to use one of the methods of dup or clone.
I can't see what I'm missing.
Any suggestions ?
Thanks.