ta539tg70
ta539tg70

Reputation: 317

Table relations with Rails + React

My Users table (has many :tweets) has following columns:
id, user_name, email, password, created_at, update_at.

and my Tweets table (belongs to :user) has following columns:
id, user_id, tweet, create_at, update_at.

Now I'm making a React project that looks like:

import React from 'react'

class Tweet extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tweet: this.props.tweet
    };
  }
  render() {
    const tweet = this.state.tweet;
    return (
      <div>
        <p>{tweet.user_id} {tweet.created_at}</p>
        <p>{tweet.tweet}</p>
      </div>
    );
  }
}

export default Tweet; 

Is there a way to write a code so I can get the user_name via user_id? I've tried {tweet.user_id.user_name} but it doesn't work or do I have to have a user_name column in Tweets table so {tweet.user_name} would be my best answer?

Upvotes: 1

Views: 357

Answers (2)

ta539tg70
ta539tg70

Reputation: 317

I was able to solve this problem by including users information in my API like so:

def index
  tweets = Tweet.all.where(user_id: current_user.id)
  respond_to do |format|
    format.html
    format.json { render json: tweets.to_json(:include => :user) }
  end
end

This way I can get the user_name within my React component with {tweet.user.user_name}.

Upvotes: 0

Shawn Andrews
Shawn Andrews

Reputation: 1442

I wouldn't recommend adding another user_name column to the table because its bad database design since you already have the user_id and can lookup user info from based on that id.

Option #1: I don't know what your parent component looks like calling your Tweet component, but if it has access to the user_name then i would pass it down along with the Tweet data via <Tweet tweet={someTweet} username={someUser}>.

Option #2: After you pull your Tweet data, perform another request to get the user_name of all Tweets based on the tweet's user id. Add this user_name to the shape of the Tweet object in React, then your Tweet component will have access to the user_name via tweet.user_name and you don't need to change your Tweet table.

Upvotes: 1

Related Questions