[英]Ruby on Rails and eager loading model associations (to include or not to include)?
[英]Rails include model associations
有沒有一種方法可以加載模型關聯而不會急於加載? 我試圖將包含模型關聯的對象推送到瀏覽器。
push_to_user
將@todo
對象推@todo
瀏覽器。 一個javascript偵聽器將讀取數據並打印出來。
我遇到的問題是@todo
不包含其模型關聯(例如“類別”)。 我該如何收錄?
@todo = Todo.find(1)
puts @todo.item.categories # eager load categories. works
# push object to pusher
Pusher.push_to_user(@todo, user)
# custom pusher method
def self.push_to_user(todo, user)
Pusher['private-1'].trigger('activity', {:todo => todo, :user => user})
end
# Browser
console.log(todo) # categories are missing
謝謝皮特
我認為最好使用以下類別添加新密鑰:
def self.push_to_user(todo, user)
Pusher['private-1'].trigger('activity', {:todo => todo, :categories => todo.categories, :user => user})
end
您可以使用:include => categories
在待辦事項上調用#serializable_hash
方法。
def self.push_to_user(todo, user)
Pusher['private-1'].trigger('activity', {:todo => todo.serializable_hash(:include => :categories), :user => user})
end
我不測試此解決方案,但可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.