0

在模型中,我有:如何將關聯加載到實例變量中?

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_component的觀點(但應該有任何區別):

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

但是它並沒有將關聯的數據傳遞給視圖(react_component),只有主模型。

我以前經歷過這個,沒有反應的前端,也沒有工作。什麼可能是錯的?

+0

它傳遞一個空數組,是否或拋出一個錯誤? –

+0

我可以使用@caledar_items,但它不包含關聯人員和文檔。謝謝 – Aurimas

+1

哦,那應該很容易。試試'CalendarItem.includes().where()'。你有訂單落後。 –

回答

1

問題不在於實例變量中的數據,而在於序列化。

如果不是字符串,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 
+0

謝謝,它看起來像它的作品!除了現在@react_component_props是部分對象部分json,所以我需要在前端做一些不太整潔的後期處理。任何使@react_component_props成爲對象的方法? (包括關聯)..我猜這是因爲'.to_json'被調用兩次然後(?) – Aurimas

+0

忘掉它,它的工作原理是這樣的:'@calendar_items = calendar_items.as_json(include:[:people,:文件])'哪裏'calendar_items'是本地變量而不是實例。 – Aurimas

+0

如果您可以將其添加到解決方案中,那麼我可以在使用時接受它。 ...'as_json'在這裏效果更好 – Aurimas

0

溶液 - 解決方法是添加as_json和包括在那裏的associatiosn:

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

該負載/串行化的關聯按預期方式。

相關問題