Help us help you! Please choose one:
react-rails, so I've included the stack trace and the exact steps which make it crash.react-rails with another library, but I'm having trouble. I've described my JavaScript management setup (eg, Sprockets, Webpack...), how I'm trying to use this other library, and why it's not working.(Describe your issue here)
I am trying to an array of posts which have several comments belongs each posts to a component. I already tested that I can't use post.comments within the component. One solution I can think of is to create a hash with post.id as key and an array of comment instances as value. Then I will be able to get to right comment array as long as I know the post_id. I wonder if there is a better to do it.
Usually, I handle this by including the children (comments) with the parent (post). For example:
<!-- include the comments in each post's JSON: -->
<% posts_json = @posts.include(:comments).map { |post| post.as_json.merge({comments: post.comments.as_json}) } %>
<!-- then pass the JSON to React: -->
<%= react_component("PostsList", {posts: posts_json}) %>
That way, you _can_ use post.comments in the component.
Would that work in your case?
It is almost correct. Just a few changes to make it works:
<% posts_json = Post.includes(:comments).map { |post| post.as_json.merge({comments: post.comments.as_json}) } %>
Thank you so much, @rmosolgo
Glad it worked!
Most helpful comment
Usually, I handle this by including the children (comments) with the parent (post). For example:
That way, you _can_ use
post.commentsin the component.Would that work in your case?