Rails link not loading properly

My parent class sometimes does not load all its children in the after_save child.

I have two models:

 class Parent < ActiveRecord::Base has_many :children def update_something # explained below end end class Child < ActiveRecord::Base belongs_to :parent after_save :tell_parent_to_update def tell_parent_to_update parent.update_something end end 

I have a test I'm working on, which only checks 2 things. parent.children.count and parent.children.length . Both should be 4. I understand that the count is sometimes different, but (as far as I know) it should not be here.

If I define update_something to just update_something over children :

 def update_something children.each do |child| end end 

the test fails - the loop will be executed once (and will return an array of one child - the first child created).

Otherwise, I can put any code if it does not mention children , and it will work. This is like a challenge for children forcing the association to download the wrong thing.

Forced reboot fixes it:

 def update_something children(true).each do |child| end end 

but these are hackies, and I would rather fix the root problem if possible.

Is this my mistake or the mistake of the rails (and if so, can I do this to get around this?)

I doubt this is important, but it is a test environment using sqlite3. Although it will also fail in the dev environment if I create and test entries in the same developer console session.

+8
ruby ruby-on-rails ruby-on-rails-4
source share
2 answers

Draw in the dark, but you may need inverse_of , which, I believe, stores related objects in one memory block, in contrast to the various blocks, a standard approach will be created:

 #app/models/parent.rb class Parent < ActiveRecord::Base has_many :children, inverse_of: :parent ... end #app/models/child.rb class Child < ActiveRecord::Base belongs_to :parent, inverse_of: :children ... end 

In my own experience, I found that inverse_of allows inverse_of to call associative data in other models. For example, calling parent.update_something without inverse_of will either result in an error (if parent not been explicitly defined), or you will have to create the parent object again.

Here is a good entry here .

-

I will delete the answer if this does not help.

+3
source share

This is probably due to the fact that the children of the parent are loaded at some point in your code before tell_parent_to_update runs.

parent.children.count will execute the SQL query and return # the children present in the database, and parent.children.length will return the length of the child array (which is probably already loaded with impatience).

I would advise you to manually try to save 1 child from the rails console and see if the length and number of children in update_something are the same. If so, your test probably doesn't work because of the code in front of it.

0
source share

All Articles