Note that there are some explanatory texts on larger screens.

plurals
  1. PORedmine Plugins - Detecting enabling and disabling of modules
    text
    copied!<p>I'm working with an external framework (redmine) which has one <code>Project</code> model that has_many <code>EnabledModules</code>.</p> <p>Projects can have EnabledModules "attached" or "removed" via the module names, like this:</p> <pre><code>class Project &lt; ActiveRecord::Base ... has_many :enabled_modules, :dependent =&gt; :delete_all ... def enabled_module_names=(module_names) enabled_modules.clear module_names = [] unless module_names &amp;&amp; module_names.is_a?(Array) module_names.each do |name| enabled_modules &lt;&lt; EnabledModule.new(:name =&gt; name.to_s) end end end </code></pre> <p>I'd like to detect when new modules are attached/removed via callbacks on <code>EnabledModule</code>, and not modify the "original source code" if possible.</p> <p>I can detect "attachments" like this:</p> <pre><code>class EnabledModule &lt; ActiveRecord::Base belongs_to :project after_create :module_created def module_created logger.log("Module attached to project #{self.project_id}") end end </code></pre> <p>I thought that a <code>before_destroy</code> would work for detecting removals, but it will not. This happens because the <code>enabled_modules.clear</code> call on <code>Project.enabled_module_names=</code>, doesn't invoke 'destroy' on the modules. It just sets their <code>project_id</code> to nil. So I figured I should use a <code>after_update</code> or <code>before_update</code>.</p> <p>If I use <code>after_update</code>, how can I get the 'previous' <code>project_id</code>?</p> <p>If I use <code>before_update</code>, how can I differentiate between modules that are 'just updated' and modules whose project_id is going to be reset to nil?</p> <p>Should I use a totally different approach here?</p> <p>EDIT: I just <a href="https://stackoverflow.com/questions/607069/using-activerecord-is-there-a-way-to-get-the-old-values-of-a-record-during-after/607139#607139">found out</a> that I could get the old values with '_was' (i.e. <code>self.project_was</code>). However, <code>collection.clear</code> doesn't seem to trigger update callbacks. Any other solutions?</p> <p>EDIT 2: Changed title</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload