How associations are updated with Synchromesh and ReactiveRecord

65 Views Asked by At

How do you get Synchromesh to update Reactive Record associations?

If you consider the following model:

# models/public/post.rb
class Post < ActiveRecord::Base
  has_many :comments
end

# models/public/comments.rb
class Comment < ActiveRecord::Base
  belongs_to :post
end

And a component that is rendering all Posts and Comments:

def render
  ul do
  Todo.all.each do |todo|
    li { todo.title }
    ul do
      todo.things.each do |thing|
        li { thing.name }
      end
    end
  end
end

The behaviour I am seeing is that any update to a Post or Comment is correctly pushed to the client and the component renders the update correctly.

However, if a new Thing is created (for a Todo being rendered), the new record arrives as a pushed notification but the list of things is not updated dynamically. (A page refresh does render the new Thing).

I have tried adding a scope to Todo but this does not make a difference.

scope :all_with_things, -> () { joins(:things) }, [Thing]

What is the best way of getting ReactiveRecord and Synchromesh to recognise a new Thing belonging to a Todo?

1

There are 1 best solutions below

1
On

I believe I worked out the answer. You need to use a scope when rendering the collection.

So in the model:

# models/public/comments.rb
class Comment < ActiveRecord::Base
  belongs_to :post
  scope :for_post, -> (post_id) { where(post_id: post_id)  }
end

And then when rendering the collection:

Todo.all.each do |todo|
    li { todo.title }
    ul do
      Comment.for_post(post.id).each do |comment|
        li { comment.body }
    end
  end
end

And with that it all works.