【问题标题】:Losing relationships from activerecord model when converting to javascript via reactjs通过 reactjs 转换为 javascript 时从 activerecord 模型中丢失关系
【发布时间】:2026-01-04 13:15:02
【问题描述】:

我正在使用 rails + react via rails-react https://github.com/reactjs/react-rails

请在下面查看我的模型:

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

这些都按预期工作,并在 rails 控制台中得到确认。这就是事情停止工作的地方。

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

当此处发生 ruby​​ -> javascript 转换时,tweets 中的所有推文均不包含 scores 关系,因此我无法访问它们。

tweet.scores === undefined

【问题讨论】:

    标签: javascript ruby-on-rails ruby reactjs


    【解决方案1】:

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

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

    然后在视图中:

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

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

    【讨论】:

    • 有更好的方法吗?
    • 您可以为推文自定义to_h,以便能够包含分数
    最近更新 更多