在View中检查加入

时间:2012-01-16 09:03:24

标签: ruby-on-rails ruby-on-rails-3

我有类似

的东西
<% @users.each do |u| %>
  ...
  <% @interests.each do |i| %>
    <% if i joins u in interests_users %> <-- That is not working that way! = Problem
      ...
      <% i.id %>
      ...
    <% end %>
  <% end %>
  ...
<% end %>

我需要输出每个用户在interest_users中加入用户的兴趣ID。但我不能为每个用户使用sql查询,因为这对服务器来说太多了,所以我查询整个兴趣表并希望在视图中过滤它。 任何人都有一个简单的解决方案吗?

1 个答案:

答案 0 :(得分:0)

您认为这也是以视图为中心的 - 这是一个数据问题,所以模型应该处理它。

我猜你在用户和兴趣之间有一个n-m关系,兴趣用户在中间加入了表格。模型应该定义这样的关系:

class User < ActiveRecord::Base
  has_and_belongs_to_many :interests
end

class Interest ...
  has_and_belongs_to_many :users
end

这是使用has_and_belongs_to_many(HABTM)。然后,模型已经处理“选择”每个用户“在”上的兴趣,只需用user_instance.interests查询它们,即执行

<% @users.each do |u| %>
  ...
  <% u.interests.each do |i| %>

如果这会为每个用户生成兴趣查询,您可以在获取用户时急切地加载数据:

@users = User.includes(:interests).all

编辑:

哦,是的,如果你想列出所有兴趣并标记用户已经关联的东西,那么这样的东西应该有效:

@interests.each do |interest|
  if u.interests.include?(interest) ...