How can I do a LEFT OUTER JOIN using Rails ActiveRecord?

前端 未结 8 1039
终归单人心
终归单人心 2021-02-05 06:42

I don\'t have any ideas. Could you give me any clues (like reference sites). Any help will be appreciated.

Model1: GROUP         


        
相关标签:
8条回答
  • 2021-02-05 07:18

    It might be quite important to mention that using includes has possibly unwanted side-effects.

    if the filtered association is subsequently scoped, all of the original filtering disappears

    As it turns out, by scoping on the filtered association we’ve lost any filtering-as-side-effect that we attained from includes. And it’s not because of how we searched, either.

    Make sure to read the complete article and alternatively there's a gem for that.

    0 讨论(0)
  • 2021-02-05 07:19

    Rails 5+ allows you to do the following:

    Group.left_outer_joins(:user_group_cmb)
    

    http://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-left_joins

    0 讨论(0)
  • 2021-02-05 07:21

    I believe an includes will use a LEFT OUTER JOIN query if you do a condition on the table that the includes association uses:

    Group.includes(:user_group_cmb).where(user_group_cmbs: { user_id: 1 })
    
    0 讨论(0)
  • 2021-02-05 07:26

    Use has_and_belongs_to_many if you just need to link users to groups. Use has_many :through if you need to store additional membership information.

    Example:

    class User < ActiveRecord::Base
      has_and_belongs_to_many :groups
    end
    
    class Group < ActiveRecord::Base
      has_and_belongs_to_many :users      
    end
    
    0 讨论(0)
  • 2021-02-05 07:31

    Use a custom joins statement:

    Group.joins("left outer join user_group_cmbs as cmb on groups.id = cmb.group_id")
      .where("cmb.user_id = ?", 1)
    
    0 讨论(0)
  • 2021-02-05 07:33

    Couldn't comment to an earlier answer because well I don't have 50 reputation. But here's how it worked for me when I ran into below error

    includes-referenced relation raises a StatementInvalid exception, complaining it misses a FROM-clause entry. I need to add an explicit call to join, which defaults to being inner.

    I had to use .references and mention the table name or for it get added to the FROM-clause

    0 讨论(0)
提交回复
热议问题