通过reactjs转换为javascript时,从activerecord模型中丢失关系

时间:2021-10-19 09:13:39

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

我正在使用rails +反应通过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.

这些都是按预期工作并在rails控制台中确认。事情停止了。

<%= 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.

当ruby - > javascript转换发生时,推文中的推文都没有包含得分关系,所以我无法访问它们。

tweet.scores === undefined

1 个解决方案

#1


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):

我希望这是由Tweet模型转换为json而没有得分关联引起的。您可以尝试使用jbuilder或to_json方法手动添加它。在你的控制器中(使用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.

我知道在#to_json上使用JSON.parse会很难看,但看看是否有效。如果是这样,你可能能够使用find_by_sql子查询重构,甚至可能只使用Tweet.includes(:scores)而不是Tweet.all。

#1


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):

我希望这是由Tweet模型转换为json而没有得分关联引起的。您可以尝试使用jbuilder或to_json方法手动添加它。在你的控制器中(使用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.

我知道在#to_json上使用JSON.parse会很难看,但看看是否有效。如果是这样,你可能能够使用find_by_sql子查询重构,甚至可能只使用Tweet.includes(:scores)而不是Tweet.all。