代码之家  ›  专栏  ›  技术社区  ›  Dex

从联接返回所有列的Rails 3

  •  6
  • Dex  · 技术社区  · 14 年前

    我试图联接两个表并返回所有列,而不仅仅是与模型关联的列。

    我有这样的东西,看起来像这样:

    Comment.joins(:user).select("*")
    

    SQL看起来很好,但它仍然只返回注释,而不返回与之相关联的任何用户信息。

    我怎样才能找回 * 而不仅仅是 comments.*

    4 回复  |  直到 11 年前
        1
  •  8
  •   rwilliams    14 年前

    怎么样

    comments = Comment.includes(:user).all
    

    现在 comments 将是一个数组,因此您必须循环访问它才能看到所有用户。

    #won't work
    comments.user 
    
    #should work
    comments[0].user
    
    comments.each do |comment|
        puts comment.user.name #or whatever
    end
    
        2
  •  2
  •   Scott    14 年前

    这应该有效:

    comments = Comment.joins(:user).includes(:user)
    

    但我认为正在发生的是,如果您在控制台窗口中查看输出,我认为控制台输出只反映/检查返回的根级别对象。

    comments.user
    

        3
  •  1
  •   Cory    14 年前