Complex JOIN with ActiveRecord and Rails 3

前端 未结 2 1379
不思量自难忘°
不思量自难忘° 2021-02-06 03:55

I have the following models:

class User < ActiveRecord::Base
  has_many :memberships
  has_many :groups, :through => :memberships
end

class Group < Act         


        
相关标签:
2条回答
  • 2021-02-06 04:43

    You can get closer without changing your model at all, by removing the unused join from your call:

    Post.joins(group: :memberships).where(memberships: { user_id: 1 })
    

    compiles to SQL

    SELECT "posts".* FROM "posts"
    INNER JOIN "groups" ON "groups"."id" = "posts"."group_id"
    INNER JOIN "memberships" ON "memberships"."group_id" = "groups"."id" 
    WHERE ("memberships"."user_id" = 1)
    
    0 讨论(0)
  • 2021-02-06 04:49

    something like this should work for you, although it requires mixing in a little raw SQL

    Post
      .joins("INNER JOIN memberships ON memberships.group_id = posts.group_id")
      .where(:memberships => {:user_id => current_user.id})
    
    0 讨论(0)
提交回复
热议问题