Rails 3 - 处理来自几个表的数据
我正在解决一个问题,如何打印一个表中的项目适当地打印第二个表中的项目。
在“TabA”中我有 id: 1 2 3 4
在“TabB”中,我有 tab_a_id: 2 3 3 3 3 3 4
具体来说,我的情况如下:
as_controller
@info_a = TabA.all(:joins => :bs, :conditions => ["city = ?", 0])
view
<% for info in @a %>
<tr>
<td><%= info.id %></td>
<td><%= info.email %></td>
<td><%= HERE I WOULD LIKE TO PRINT COUNT ITEMS FROM TabB ('bs' controller, 'b' model) %></td>
</tr>
<% end %>
我试图找到如何打印例如,对于“TabA”中 ID 号为 3 的项目,“TabB”中的行数(在 TabB 中是值 3 的 5 倍)。
提前致谢!
编辑:解决方案 - info.tabb.size
I am solving a question, how to print for an item in one table appropriately items from second table.
In 'TabA' I have id:
1
2
3
4
In 'TabB' I have tab_a_id:
2
3
3
3
3
3
4
Specifically, my situation looks this:
as_controller
@info_a = TabA.all(:joins => :bs, :conditions => ["city = ?", 0])
view
<% for info in @a %>
<tr>
<td><%= info.id %></td>
<td><%= info.email %></td>
<td><%= HERE I WOULD LIKE TO PRINT COUNT ITEMS FROM TabB ('bs' controller, 'b' model) %></td>
</tr>
<% end %>
And I am trying to found, how to print e.g. for item with ID number 3 from 'TabA' the count of lines in 'TabB' (in TabB is 5 times the value 3).
Thanks in advance!
EDIT: solution - info.tabb.size
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不在 A 模型和 B 模型之间建立关联呢?这样,您就可以执行以下操作:
abcount
。你的方法的问题是你从数据库请求所有行,Rails 用 AR 对象包装它们,将它们放入数组中,然后计算它的大小。另一方面,
count
告诉数据库对结果进行计数并仅返回一个数字,因此速度要快得多。Why don't you set up an association between A and B models? This way, you could do this:
a.b.count
.The problem of your approach is that you request all the rows from the DB, Rails wraps them with AR objects, put them into array and than calculate the size of it.
count
on the other hand tells the DB to count the results and returns only one number so it is much more faster.