LEFT OUTER joins in Rails 3

后端 未结 8 1914
自闭症患者
自闭症患者 2020-11-27 12:31

I have the following code:

@posts = Post.joins(:user).joins(:blog).select

which is meant to find all posts and return them and the associat

相关标签:
8条回答
  • 2020-11-27 12:54

    Good news, Rails 5 now supports LEFT OUTER JOIN. Your query would now look like:

    @posts = Post.left_outer_joins(:user, :blog)
    
    0 讨论(0)
  • 2020-11-27 12:56

    Use eager_load:

    @posts = Post.eager_load(:user)
    
    0 讨论(0)
  • 2020-11-27 12:57

    You can do with this with includes as documented in the Rails guide:

    Post.includes(:comments).where(comments: {visible: true})
    

    Results in:

    SELECT "posts"."id" AS t0_r0, ...
           "comments"."updated_at" AS t1_r5
    FROM "posts" LEFT OUTER JOIN "comments" ON "comments"."post_id" = "posts"."id"
    WHERE (comments.visible = 1)
    
    0 讨论(0)
  • 2020-11-27 13:00
    class User < ActiveRecord::Base
         has_many :friends, :foreign_key=>"u_from",:class_name=>"Friend"
    end
    
    class Friend < ActiveRecord::Base
         belongs_to :user
    end
    
    
    friends = user.friends.where(:u_req_status=>2).joins("LEFT OUTER JOIN users ON users.u_id = friends.u_to").select("friend_id,u_from,u_to,u_first_name,u_last_name,u_email,u_fbid,u_twtid,u_picture_url,u_quote")
    
    0 讨论(0)
  • 2020-11-27 13:02

    I'm a big fan of the squeel gem:

    Post.joins{user.outer}.joins{blog}
    

    It supports both inner and outer joins, as well as the ability to specify a class/type for polymorphic belongs_to relationships.

    0 讨论(0)
  • 2020-11-27 13:11
    @posts = Post.joins("LEFT OUTER JOIN users ON users.id = posts.user_id").
                  joins(:blog).select
    
    0 讨论(0)
提交回复
热议问题