Method callback in another model

I have Group, Membership, and User models. Associated with has_many: through union. The route is wise, membership is nested within the group.

I want that whenever someone joins or leaves a group (i.e. creates or destroys membership), initiates a group check to check what the dominant language is (this is an attribute in the user model) and update the language attribute in the model groups.

I have a method called define_language in a Group model that works independently.

Now I need to call this method from the Membership model, I was thinking of doing this using after_save callback , but I had a problem referring to this method on the (different) Group model method .

I put this method in a group model, not a membership model, because I feel that semantically it has little to do with membership. Is this assumption wrong? How can I effectively solve this problem?

+5
source share
2 answers

One of the methods:

class Membership < ActiveRecord::Base
  belongs_to :group
  before_save :update_group_language

  ...

  private

  def update_group_language
    self.group.define_language
  end
end

I do not see how this can work:

class Membership < ActiveRecord::Base
   belongs_to :group
   before_save group.define_language
end

The problem with this is that property_to is only checked by Ruby when rails is loaded first.

+2
source

I get it, you just ran it in Memberhip.rb

 before_save group.define_language

And tadaa! It will call define_language in the Group.rb model.

Optionally, you can add these to determine the relationship:

before_save group.define_language "id = #{group_id}"
+1
source

All Articles