Rails 3.1 将对象添加到 find_by_sql 返回的数组中/无法在 erb 文件中显示
我正在将 php 应用程序移植到 Rails,因此我有一组 sql 语句,我将它们转换为 find_by_sql 的。我看到它返回了我调用它的类型的对象集合。然后我想做的是迭代这个集合(大概是一个数组)并添加特定对象的实例,如下所示:
#class is GlobalList
#sql is simplified - really joining across 3 tables
def self.common_items user_ids
items=find_by_sql(["select gl.global_id, count(gl.global_id) as global_count from main_table gl group by global_id"])
#each of these items is a GlobalList and want to add a location to the Array
items.each_with_index do |value,index|
tmp_item=Location.find_by_global_id(value['global_id'])
#not sure if this is possible
items[index]['location']=tmp_item
end
return items
end
控制器
#controller
@common_items=GlobalList.common_items user_ids
视图
#view code - the third line doesn't work
<% @common_items.each_with_index do |value,key| %>
<%=debug(value.location) %> <!-- works -->
global_id:<%=value.location.global_id %> <!-- ### doesn't work but this is an attribute of this object-->
<% end %>
所以我有 3 个问题:
1. items 是数组吗?它说这是通过调用 .class 但不确定
2. 我能够添加这些 GlobalList 项目的位置。但是在视图代码中,我无法访问位置的属性。我如何访问它?
3.我知道这很难看——有没有更好的模式来实现这个?
I'm porting a php app to rails so I have a set of sql statements that I'm converting to find_by_sql's. I see that it returns a collection of objects of the type that I called on it. What I'd like to do is then iterate through this collection (presumably an array) and add an instance of a specific object like this:
#class is GlobalList
#sql is simplified - really joining across 3 tables
def self.common_items user_ids
items=find_by_sql(["select gl.global_id, count(gl.global_id) as global_count from main_table gl group by global_id"])
#each of these items is a GlobalList and want to add a location to the Array
items.each_with_index do |value,index|
tmp_item=Location.find_by_global_id(value['global_id'])
#not sure if this is possible
items[index]['location']=tmp_item
end
return items
end
controller
#controller
@common_items=GlobalList.common_items user_ids
view
#view code - the third line doesn't work
<% @common_items.each_with_index do |value,key| %>
<%=debug(value.location) %> <!-- works -->
global_id:<%=value.location.global_id %> <!-- ### doesn't work but this is an attribute of this object-->
<% end %>
So I have 3 questions:
1. is items an Array? It says it is via a call to .class but not sure
2. I am able to add location these GlobalList items. However in the view code, I cannot access the attributes of location. How would I access this?
3. I know that this is pretty ugly - is there a better pattern to implement this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将从 sql 查询中的位置获取您需要的任何数据,这样您就可以避免 n +1问题
然后在视图中:
如果你想保持它接近原样,我会:
然后在视图中:
I would get any data you need from locations in the sql query, that way you avoid the n+1 problem
Then in the view:
If you want to keep it close to as is, I would:
Then in the view: