Kylee
Kylee

Reputation: 1675

Losing relationships from activerecord model when converting to javascript via reactjs

I'm using rails + react via rails-react https://github.com/reactjs/react-rails

Please see my models below:

class Interest < ActiveRecord::Base
  has_many :tweets
  has_many :scores
end

class Tweet <  ActiveRecord::Base
  belongs_to :interest
  has_many :scores
end

class Score <  ActiveRecord::Base
  belongs_to :interest
  belongs_to :tweet
end

These are all working as expected and confirmed in the rails console. Here is where things stop working.

<%= react_component('MainComponent', { :tweets => Tweets.all }) %>

When the ruby -> javascript conversion happens here none of the tweets in tweets contain the scores relationship so I can't access them.

tweet.scores === undefined

Upvotes: 1

Views: 167

Answers (1)

PhilVarg
PhilVarg

Reputation: 4821

I expect this is being caused by the Tweet model being converted to json without the scores association. You can try adding it manually with jbuilder or the to_json method.
In your controller (using to_json):

@tweetProps = JSON.parse Tweet.all.to_json(include: :scores)

and then in the view:

<%= react_component('MainComponent', { :tweets => @tweetProps }) %>

I know its kind ugly to use JSON.parse on #to_json but see if this works. If it does, you'll probably be able to refactor with a find_by_sql subquery or maybe even just using Tweet.includes(:scores) instead of Tweet.all.

Upvotes: 2

Related Questions