K
K
Kirill Bobykin2015-09-08 09:28:48
Ruby on Rails
Kirill Bobykin, 2015-09-08 09:28:48

How to change a model in another model's callback?

I have Category, Subcategory and Group models linked like this:

class Category
  has_many :subcategories
  has_many :groups
end

class Subcategory
  belongs_to :category
  has_many :groups
end

I want to force a subcategory to inherit category groups and I do it like this:
class Category
  has_many :subcategories
  has_many :groups
  after_save :pass_to_subcategories

  private
  def pass_to_subcategories
    subcategories.map do |sc| 
      sc.groups = groups
    end
  end

end

But at runtime of the callback, groups is an empty array, even though the save operation at that point should have saved the groups for this instance. Obviously I'm doing something wrong. Please help. Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel Kononenko, 2015-09-08
@premas

even though the save operation at that point should have saved the groups for that instance

How do you keep what you affirm? We need to wrap saving Category and Subcategory in one transaction.

J
Jeiwan, 2015-09-08
@Jeiwan

after_save

Don't you think that these lines contradict each other?
In fact, there is no need
for a subcategory relationship here. It is enough to create a method:
class Subcategory
  def groups
    category.groups
  end
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question