【问题标题】:Ruby Joins and Select but can't see all that is selected, why?Ruby Joins and Select 但看不到所有选择,为什么?
【发布时间】:2011-09-08 07:13:12
【问题描述】:

我有这个代码...

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..still learning..newbie! xP

【问题讨论】:

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


    【解决方案1】:

    实际上在所有实例中还有更多,但您看到的是调用 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)
    

    【讨论】:

    • 检查是否不对数据库进行额外查询
    • 它没有。自定义选择将所有返回的列存储在实例中。
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      例子

      ...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>
      

      【讨论】:

        猜你喜欢
        • 2012-10-24
        • 1970-01-01
        • 1970-01-01
        • 2011-09-17
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-18
        相关资源
        最近更新 更多