Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/420.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
通过reactjs转换为javascript时失去与activerecord模型的关系_Javascript_Ruby On Rails_Ruby_Reactjs - Fatal编程技术网

通过reactjs转换为javascript时失去与activerecord模型的关系

通过reactjs转换为javascript时失去与activerecord模型的关系,javascript,ruby-on-rails,ruby,reactjs,Javascript,Ruby On Rails,Ruby,Reactjs,我通过rails react使用rails+react 请看下面我的模型: 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

我通过rails react使用rails+react

请看下面我的模型:

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

我认为这是由于Tweet模型在没有分数关联的情况下被转换为json造成的。您可以尝试使用jbuilder或
到\u json
方法手动添加它。
在控制器中(使用to_json):

然后在视图中:

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

我知道在
#上使用
JSON.parse
to_JSON
有点难看,但看看这是否有效。如果是这样的话,您可能可以使用
find\u by\u sql
子查询进行重构,或者甚至可以只使用
Tweet.includes(:scores)
而不是
Tweet.all

有没有更好的方法可以做到这一点?您可以为tweet创建一个自定义的
to_h
,以便能够包含分数
tweet.scores === undefined
@tweetProps = JSON.parse Tweet.all.to_json(include: :scores)
<%= react_component('MainComponent', { :tweets => @tweetProps }) %>