簡體   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