LEFT OUTER joins in Rails 3

后端 未结 8 1915
自闭症患者
自闭症患者 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 13:18

    By default when you pass ActiveRecord::Base#joins a named association, it will perform an INNER JOIN. You'll have to pass a string representing your LEFT OUTER JOIN.

    From the documentation:

    :joins - Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed), named associations in the same form used for the :include option, which will perform an INNER JOIN on the associated table(s), or an array containing a mixture of both strings and named associations.

    If the value is a string, then the records will be returned read-only since they will have attributes that do not correspond to the table‘s columns. Pass :readonly => false to override.

    0 讨论(0)
  • 2020-11-27 13:19

    There is a left_outer_joins method in activerecord. You can use it like this:

    @posts = Post.left_outer_joins(:user).joins(:blog).select
    
    0 讨论(0)
提交回复
热议问题