Update deeply nested model upon save

时间:2016-05-17 11:13:36

标签: ruby-on-rails ruby-on-rails-4 activerecord cocoon-gem

I'm attempting to update a deeply nested model from a model that is itself nested using cocoon. (Don't worry, I'll clarify)

I have three Models: Stock Stockholder and Folder. Stock has_many :stockholders, which are all nested via cocoon in a form_for @stock. Stockholder has_one :folder.

Within my stock form, I have a table that lists out stockholders where I can add new ones (to reiterate, via cocoon). To create a Folder for each new Stockholder, I have a before_create filter in my Stockholder model that creates a new Folder for each new Stockholder (see below)

before_create :build_default_folder

def build_default_folder
    logger.debug "Inside build_default_folder"
    build_folder(name: "#{self.holder_index}. #{self.holder_name}", company_id: self.warrant.company.id, parent_id: self.warrant.company.folders.find_by_name("#{self.warrant.security_series} #{self.warrant.security_class} Warrant").id)
    true
end

All of that works very well.

The problem

Is that I would like to add a method that updates the Folder attributes according to any changes in the stockholder information (say they change the name or something). To this end, I've attempted to add the following.

before_save :update_default_folder

def update_default_folder
    logger.debug "Inside update_default_folder"
    self.folder.update_attributes(name: "#{self.holder_index}. #{self.holder_name}", company_id: self.warrant.company.id, parent_id: self.warrant.company.folders.find_by_name("#{self.warrant.security_series} #{self.warrant.security_class} Warrant").id)
    true
end

This however doesn't work and (particularly puzzling to me) is that before_save doesn't even seem to be firing. My best guess would be that this is because stockholder is itself nested using cocoon (but I could be completely wrong about this).

Anyway, how might I achieve the desired functionality? Thanks for any suggestions.

0 个答案:

没有答案