How ReactJS Handles Rails Active Record Associations

I am repeating user message elements. I can list the elements, but not their profile, based on my relationship:

Message Model:

belongs_to :user 

Profile Model:

 belongs_to :user 

User Model:

 has_many :posts has_one :profile 

PostsController:

 class PostsController < ApplicationController respond_to :json before_action :set_post, only: [:show, :edit, :update, :destroy] before_action :only_current_user, except:[:show, :interest] # GET /posts # GET /posts.json def index @user = User.friendly.find( params[:user_id] ) end [...] end 

Index Page Controller:

 class PagesController < ApplicationController respond_to :json def index @users = User.all @posts = Post.all.order("created_at DESC") end [...] end 

Without JS, I get the values ​​with:

 <% @posts.each do |s| %> <%= s.user.profile.business_name %> <%= s.post_type %> <%= s.<all others> %> <% end %> 

Now, using React, I can use rock with rock rails to do this:

 var Posts = React.createClass({ render: function() { var createItem = (p) => ( <div className="row"> {p.post_type} {p.foobar} {p.user.name} //this does not work </div> ); return ( <div className="panel"> {this.props.posts.map(createItem)} </div> ); } }); 

index.html.erb:

 <%= react_component('Posts', { posts: @posts } %> 

I thought I had an answer, but it just spits out all users when I only need a user with a related message:

 <%= react_component('Posts', { posts: @posts, users: @users } %> 

Then I added props to js, ​​but that is not what I want.

There seems to be a key in my console that I'm trying to figure out:

“Warning: each child in an array or iterator must have a unique“ key. ”Check the message rendering method.

+7
javascript ruby-on-rails reactjs ruby-on-rails-4
source share
1 answer

I do not think the warning has anything to do with the problem, but in order to get rid of it, you can add the key to the React component as follows:

 var Posts = React.createClass({ render: function() { var createItem = (p) => ( <div className="row" key={p.id}> {p.post_type} {p.foobar} {p.user.name} //this does not work </div> ); return ( <div className="panel"> {this.props.posts.map(createItem)} </div> ); } }); 

Regarding the real issue, try changing the @posts to something like @posts = Post.all.includes(:user).as_json(include: { user: { only: [:name] } })

I assume you are just requesting messages. By default, as_json (the method that is called when json returns data) does not contain associations, so you will not get anything on the reaction side.

+12
source share

All Articles