通过reactjs转换为javascript时失去与activerecord模型的关系
我通过rails react使用rails+react 请看下面我的模型:通过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
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 }) %>