React-rails: Is it possible to use association in component -- a Rails app

Created on 1 Sep 2016  路  3Comments  路  Source: reactjs/react-rails

Help us help you! Please choose one:

  • [ ] My app crashes with react-rails, so I've included the stack trace and the exact steps which make it crash.
  • [ ] My app doesn't crash, but I'm getting unexpected behavior. So, I've described the unexpected behavior and suggested a new behavior.
  • [ ] I'm trying to use 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.
  • [x ] I have another issue to discuss.

(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.

Most helpful comment

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?

All 3 comments

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!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

davidlormor picture davidlormor  路  3Comments

Deekor picture Deekor  路  4Comments

chrismv48 picture chrismv48  路  3Comments

dylanitorium picture dylanitorium  路  4Comments

axhamre picture axhamre  路  3Comments