leejay100
leejay100

Reputation: 221

Show Associated Model Data with React Rails

I'm using the react-rails gem and have two models: Message and User. User has_many :messages.

In my message.js.jsx, I'd like to show the User of that message. In regular erb, it'd just be <%= message.user.name %>. How would I do this in the message.js.jsx component?

Upvotes: 3

Views: 762

Answers (2)

James B.
James B.

Reputation: 21

I agree with Unixmonkey that is the react way. You can also do it a few more ways.

@user = JSON.parse user.to_json(include: [:messages], only: [:id, :name])

As well as using componentDidMount to hit a JSON endpoint using jbuilder which you can put a timeout on if you want to update dynamically.

componentDidMount: function() {
  $.getJSON('/users/'+ this.props.id +'.json', function(user) {
    if (this.isMounted()) {
      this.setState({ user: user })
    }
  });
},

Your show.json.jbuilder under user views would look something like this:

  json.id @user.id
  json.name @user.name
  json.messages @user.messages do |message|
    json.id message.id
    json.content message.content
    json.created_at message.created_at
  end

Upvotes: 2

Unixmonkey
Unixmonkey

Reputation: 18784

You could rename your component to message.js.jsx.erb and use ERB in it, but it will only be compiled once when Rails starts up.

A more React-ish way to handle is to AJAX load the user data in componentDidMount (or a Store, if using Flux).

message.js.jsx

getInitialState: function() {
  return { user: { name: '' } };
},

componentDidMount: function() {
  $.getJSON('/users/'+ this.props.id +'.json', function(userData) {
    if (this.isMounted()) {
      this.setState({ user: userData })
    }
  });
},

You can create a Rails endpoint to return userData as JSON something like this:

users_controller.rb

def show
  @user = User.find(params[:id])
  respond_to do |format|
    format.html # default html response
    format.json { render json: @user.to_json(only: [:id, :name]) }
  end
end

See Facebook's page on this for more details

Upvotes: 2

Related Questions