Note that there are some explanatory texts on larger screens.

plurals
  1. POHMT collection_singular_ids= deletion of join models is direct, no destroy callbacks are triggered
    primarykey
    data
    text
    <p>Just ran into an issue with a has_many :through association and after/before-destroy callbacks not being triggered.</p> <p>Say, I have users, groups, and an intermediate relation called membership. I have a form that allows users to be enrolled into groups by creating a new membership record when they check off associated checkboxes. Basically an array of group_ids.</p> <p>Looks something like this:</p> <pre><code>Which group would you like to join? (check all that apply) [] Group A [] Group B [] Group C </code></pre> <p>And I wish to record actions such as joining a group or leaving a group to activity log table and do some other less important thigns.</p> <p>I have the following defined:</p> <pre><code>class Group &lt; AR::Base has_many :memberships has_many :users, :through =&gt; :memberships end class Membership &lt; AR::Base belongs_to :user belongs_to :group after_create :log_event_to_audit_table after_destroy :log_event_to_audit_table end class User &lt; ActiveRecord::Base has_many :memberships has_many :groups, :through =&gt; :memberships attr_accessible :group_ids # enables mass-assignment end </code></pre> <p>When a new membership record is created the after_create is run as expected. However, the after_destroy does not get triggered!</p> <p>After google-ing and read up the docs I discovered the reason why:</p> <blockquote> <p>"Automatic deletion of join models is direct, no destroy callbacks are triggered" - from Ruby Guides.</p> </blockquote> <p>Hmmmmmm...</p> <p>So the join model's (in this case Membership's) destroy callbacks are not being triggered. Well that's a downer. Any reason as to why?</p> <p>So my question what is the best way to work around this issue? Should I define my own membership_ids= method in User model that calls membership.destroy directly?</p> <p>Open to any suggestions about the best practices in such a scenario.</p> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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