简体   繁体   English

Rails包含模型关联

[英]Rails include model associations

is there a way to load model association without eager loading? 有没有一种方法可以加载模型关联而不会急于加载? im trying to push an object to the browser with model associations included. 我试图将包含模型关联的对象推送到浏览器。

push_to_user pushes the @todo object to the browser. push_to_user@todo对象推@todo浏览器。 a javascript listener will read the data and print it out. 一个javascript侦听器将读取数据并打印出来。

The issue im having is that @todo doesn't include its model association (eg "categories"). 我遇到的问题是@todo不包含其模型关联(例如“类别”)。 how can i include that? 我该如何收录?

@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

thanks pete 谢谢皮特

I think the better is add a new key with this categories : 我认为最好使用以下类别添加新密钥:

def self.push_to_user(todo, user)
    Pusher['private-1'].trigger('activity', {:todo => todo, :categories => todo.categories, :user => user})
end

You can call a #serializable_hash method on your todo with an :include => categories 您可以使用: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

I don't test this solution but can works. 我不测试此解决方案,但可以工作。

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

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