Rails 3 fields_用于主动加载?
我正在尝试优化(限制)视图中的查询。我正在使用 fields_for 函数。我需要引用对象的各种属性,例如用于显示目的的用户名。但是,这是一个 rel 表,所以我需要加入我的 users 表。结果是 N 个子查询,fields_for 中的每个字段 1 个。这很难解释,但我想如果我粘贴我的代码你就会明白我在问什么:
<%= form_for @election do |f| %>
<%= f.fields_for :voters do |voter| %>
<%= voter.hidden_field :id %>
<%= voter.object.user.preferred_name %>
<% end %>
<% end %>
我有大约 10,000 个用户,很多时候每次选举都会包括所有 10,000 个用户。每次加载此视图时,都会有 10,000 个子查询。我希望 fields_for 加入用户。这可能吗?
我想做类似的事情:
...
<%= f.fields_for :voters, :joins => :users do |voter| %>
...
<% end %>
...
但这当然行不通:(
I'm trying to optimize (limit) queries in a view. I am using the fields_for function. I need to reference various properties of the object, such as username for display purposes. However, this is a rel table, so I need to join with my users table. The result is N sub-queries, 1 for each field in fields_for. It's difficult to explain, but I think you'll understand what I'm asking if I paste my code:
<%= form_for @election do |f| %>
<%= f.fields_for :voters do |voter| %>
<%= voter.hidden_field :id %>
<%= voter.object.user.preferred_name %>
<% end %>
<% end %>
I have like 10,000 users, and many times each election will include all 10,000 users. That's 10,000 subqueries every time this view is loaded. I want fields_for to JOIN on users. Is this possible?
I'd like to do something like:
...
<%= f.fields_for :voters, :joins => :users do |voter| %>
...
<% end %>
...
But that, of course, doesn't work :(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您只需确保选民关系始终与选举模型中的用户连接即可。
阅读有关关联的 Rails 文档以及在模型中声明关系时可以提供的额外选项。
http://railsapi.com/doc/rails -v3.0.1/classes/ActiveRecord/Associations/ClassMethods.html#M001055
you could just ensure that the voters relationship always joins with users in the election model.
Read the Rails documentation on associations and the extra options you can provide when declaring relationships in the model.
http://railsapi.com/doc/rails-v3.0.1/classes/ActiveRecord/Associations/ClassMethods.html#M001055
所以,我不知道该怎么做,但我找到了解决方法。我在我的模型中覆盖了election.voters,以返回加入用户......
So, I have no idea how to do this, but I found a way around it. I overrode election.voters in my model to return joined on users...
您还可以创建一个加入用户的命名范围,
然后您可以使用类似
Election.with_voters.first
You can also create a named scope that joins users
then you can use something like
Election.with_voters.first