Ruby Joins和Select但是看不到所有被选中的,为什么?

时间:2011-09-08 07:13:12

标签: ruby-on-rails ruby activerecord select join

我有这段代码......

User.find :all, 
          :select => "users.id, departments.name, users.username, response_sets.id AS 'response_set_id', response_sets.survey_id, COUNT(responses.id) AS 'answers', response_sets.completed_at", 
          :joins => "LEFT JOIN departments ON users.department_id = departments.id LEFT JOIN versions ON departments.version_id = versions.id LEFT JOIN response_sets ON users.id = response_sets.user_id AND versions.survey_id = response_sets.survey_id LEFT JOIN responses ON response_sets.id = responses.response_set_id AND responses.answer_id IS NOT NULL", 
          :conditions => {:id => 4}, 
          :group => "users.id"

如果还有更多的话,那么它的归还就是[#<User id: 4, username: "3333">]吗?因为我:select ??我应该使用:include代替:joins ..还在这里学习......新手! XP

3 个答案:

答案 0 :(得分:0)

实际上在所有实例中都有更多,但您看到的是调用方法inspect的结果,并且只显示User模型中实际列的内容。但是,如果您尝试调用语句返回的其他值,您应该能够看到结果。例如:

@users.first.response_set_id # => will return the value from response_sets.id
@users.first.answers         # => will return the value from COUNT(responses.id)

答案 1 :(得分:0)

Rails中的ActiveRecord为您提供了一种ORM。这意味着您使用对象。因此,当您使用include加入其他表时,它的字段将不会出现在结果表中。要获得它们,您需要在结果查询上调用parent_table.joined_table.your_field。使用join - 字段将可用。因此,如果您加入了一些表格,最好明确地调用它们并获取它们的列 BTW读取joininclude之间的差异:find method

答案 2 :(得分:0)

实施例

...select("orders.*, cities.name AS city_name, countries.name AS country_name, customers.account_id as customer_acc").
      joins("LEFT JOIN customers ON customers.id = orders.customer_id")....

然后在视图中我可以使用[]

访问其他数据
<td><%= order[:country_name] %></td>
<td><%= order[:city_name] %></td>