For some reason to explain too long, I need to override the *_attributes=(attributes) method of my model, which accepts nested attributes for another model. For example, here are my models:
class Experience < ActiveRecord::Base accepts_nested_attributes_for :company def company_attributes=(attributes) ... end end
First, I started creating a new company every time I called this method (replacing ... with self.company = Company.new(attributes) ). Needless to say, he will go and save the new company in the database.
When I found out that I was doing this, I edited this method as follows:
def company_attributes=(attributes) self.company.nil? ? self.company = Company.new : self.company.assign_attributes(attributes) end
which seemed to be the right way (it would only create a new object if it was zero, otherwise it would just assign the changed attributes). However, while the new experience was saving the newly created company in the database, when editing the experience, it would change the attributes of the company immediately after the one-line method, but would not save it in the database.
Question 1: how do the generated methods *_attributes=(attributes) ?
Question 2: how can I change the company_attributes=(attributes) method to achieve my goal: create a new company when creating new experience and changing company attributes when editing experience. p>
thanks
source share