繁体   English   中英

如何渴望将关联加载到实例变量中?

[英]How to eager load associations into an instance variable?

在模型中,我有:

class CalendarItem < Resource
  belongs_to :schedule

  has_many :people
  has_many :documents

  acts_as_list scope: :schedule, column: :visual_position

  validates :schedule, :title, presence: true
end

然后在控制器中:

class ScheduleController < ApplicationController
  def show
    @calendar_items = CalendarItem.where(schedule: @schedule).includes(:people, :documents)
  end

  ...
end

在视图中,我正在渲染带有react-rails的react_component(但这应该有所不同):

= react_component('CalendarItemsList', calendar_items: @calendar_items)

但是,它不会将关联的数据传递给视图(react_component),而只会传递给主模型。

我以前在非反应式前端中经历过这种情况,但也没有用。 有什么事吗

问题不在于实例变量中的数据,而在于序列化。

如果不是字符串,则react_component视图帮助器将在第二个参数上调用to_json方法。 在您的情况下: {calendar_items: @calendar_items}.to_json可以递归工作,因此您需要确保@calendar_items.to_json返回预期的JSON输出。 您可以使用@calendar_items.serializable_hashrails console中对其进行测试,它会返回一个哈希值,该哈希值对于人类来说更易读。

或者,您将数据序列化为字符串,然后将其提供给react_component

我不知道Rails 5的序列化,但是它似乎类似于ActiveModelSerializers,因此您可以在序列化的输出中包括以下关系: @calendar_items.to_jso(include: [:documents]) 在ActiveModelSerializers中,您可以为每个类指定一个序列化器,并指定它们之间的关系,这些关系可以自动包括在内。

因此,一种可行的解决方案可能是:

def show
  calendar_items = CalendarItem.where(schedule: @schedule).includes(:people, :documents)
  @react_component_props = { calendar_items: calendar_items.to_json(include: [:people, :documents]) }
end

= react_component('CalendarItemsList', @react_component_props)

适度提示:您可以在CalendarItem模型上创建by_schedule范围,以便稍后使用: CalendarItem.by_schedule @schedule

编辑

如果您需要在视图中其他位置放置数据,则可以使用as_json方法:

def show
  calendar_items_scope = CalendarItem.where(schedule: @schedule).includes(:people, :documents)
  @calendar_items = calendar_items_scope.as_json(include: [:people, :documents])
end

解决方案-解决方法是添加as_json并在其中包含关联:

@calendar_items = CalendarItem.where(schedule: @schedule)
                              .as_json(include: [:people, :documents])

这将按预期加载/序列化关联。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM