我正在将一个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.是一个数组的项目?它说这是通过调用.class但不确定
2.我能够添加这些GlobalList项目的位置。但是在视图代码中,我无法访问位置的属性。我该如何获取?
3.我知道这很难看 - 有没有更好的模式来实现这个?
答案 0 :(得分:0)
我会从sql查询中的位置获取您需要的任何数据,这样就可以避免n+1 problem
@items=find_by_sql(["select locations.foo as location_foo,
gl.global_id as global_id,
count(gl.global_id) as global_count
from main_table gl
inner join locations on locations.global_id = gl.global_id
group by global_id"])
然后在视图中:
<% @items.each do |gl| %>
<%= gl.location_foo %> <-- select any fields you want in controller -->
<%= gl.global_count %>
<%= gl.global_id %>
<% end %>
如果你想保持接近原样,我会:
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"])
items.map do |value|
[value, Location.find_by_global_id(value.global_id)]
end
end
然后在视图中:
<% @common_items.each do |value,location| %>
<%=debug(location) %>
global_id:<%=value.global_id %>
<% end %>