我对ruby很新,我正在尝试使用连接方法来获取属于我的表演的表演者。使用这个简单的代码(在我的头标记内):
window.performances = <%=raw Performance.joins(:performers).to_json(:include => {:performers => {
:except => [ :created_at, :updated_at ]
}}, :except => [ :created_at, :updated_at ]) %> ;
alert(JSON.stringify(window.performances));
这很好用,除了我得到所有表演的输出两次而不是一次。 像这样:
[{"id":1,"date":"2011-12-10","location":"Malgorzaty i Zygmunta Belza","performers":[{"id":1,"name":"Wojtek Szewczuk"},{"id":2,"name":"Danuta Sroka"}]},{"id":1,"date":"2011-12-10","location":"Malgorzaty i Zygmunta Belza","performers":[{"id":1,"name":"Wojtek Szewczuk"},{"id":2,"name":"Danuta Sroka"}]},{"id":2,"date":"2011-12-10","location":"Malgorzaty i Zygmunta Belza","performers":[{"id":1,"name":"Wojtek Szewczuk"},{"id":2,"name":"Danuta Sroka"}]},{"id":2,"date":"2011-12-10","location":"Malgorzaty i Zygmunta Belza","performers":[{"id":1,"name":"Wojtek Szewczuk"},{"id":2,"name":"Danuta Sroka"}]}, ...
我假设它与存在的执行者数量有关,因此每个执行者都会从数据库中生成新结果。我只是不明白为什么会这样?
我做错了什么,如何避免我的结果中的重复。
答案 0 :(得分:1)
因为 joins
创建 duplicate values
。您使用 includes
来摆脱重复值。
window.performances = <%=raw Performance.includes(:performers).to_json(:include => {:performers => {
:except => [ :created_at, :updated_at ]
}}, :except => [ :created_at, :updated_at ]) %> ;
alert(JSON.stringify(window.performances));
includes
还可以避免 N+1
生成 DB
。
请参阅以下 Guides 了解更多信息。我希望它有所帮助!