使用三向关联查询/ has_many:通过/ join

时间:2012-12-10 14:30:16

标签: join ruby-on-rails-3.2 has-many-through

我正在使用指南/ apis /书籍教我自己Rails,但我无法通过三种方式/嵌套has_many来理解联接:通过关联。

用户群组相关联:通过会员

我在群组的多对多中也有帖子。可以将相同的帖子发布到许多组+组可以有很多帖子。

我希望能够为用户的主页做什么,显示群组的所有不同帖子 < strong>用户是。

的成员

例如。 current_user.groups.posts#我希望这很容易!!

这是我的代码。

Models:

class User < ActiveRecord::Base
  has_many :memberships
  has_many :groups, :through => :memberships
  has_many :posts  # as author of post
end

class Group < ActiveRecord::Base
  has_many :memberships
  has_many :users, :through => :memberships
  has_and_belongs_to_many :posts
end

class Membership < ActiveRecord::Base
  belongs_to :user
  belongs_to :group
end

class Post < ActiveRecord::Base
  belongs_to :user
  has_and_belongs_to_many :groups
end

的routes.rb

Myapp::Application.routes.draw do
  get "admin/index"
  devise_for :users

  resources :users do
    member do
      get :groups
    end
  end

  resources :groups do
    member do
      get :members
      post :join
      post :leave
    end
  end

  resources :posts

home_controller.rb#索引

class HomeController < ApplicationController
  before_filter :authenticate_user!

  def index
    @user = current_user
    @groups = Group.all
    @user_groups = @user.groups
    @home_page_posts = Post.joins(:groups, :user)
  end
end

这显然只是给了我一个不同的所有组中所有帖子的列表。

如果有人能指出我正确的方向。 我已经尝试了http://guides.rubyonrails.org/active_record_querying.html#joining-tables但是我没看到这些例子。

如果您需要我提供更多信息,请与我们联系。:D

2 个答案:

答案 0 :(得分:1)

我相信这就是你想要的:

Post.includes(:groups => :users).where('users.id' => current_user.id)

这将生成这样的SQL(对于current_user.id = 1):

SELECT "posts"."id" AS t0_r0, "posts"."user_id" AS t0_r1,
  "posts"."created_at" AS t0_r2, "posts"."updated_at" AS t0_r3,
  "groups"."id" AS t1_r0, "groups"."created_at" AS t1_r1,
  "groups"."updated_at" AS t1_r2, "users"."id" AS t2_r0,
  "users"."name" AS t2_r1, "users"."created_at" AS t2_r2,
  "users"."updated_at" AS t2_r3
  FROM "posts"
  LEFT OUTER JOIN "groups_posts" ON "groups_posts"."post_id" = "posts"."id"
  LEFT OUTER JOIN "groups" ON "groups"."id" = "groups_posts"."group_id"
  LEFT OUTER JOIN "memberships" ON "memberships"."group_id" = "groups"."id"
  LEFT OUTER JOIN "users" ON "users"."id" = "memberships"."user_id"
  WHERE "users"."id" = 1

另请参阅:Filter model with multiple has many through(不完全相同,但相似)

答案 1 :(得分:1)

感谢@shioyama,我最终使用他的答案为Post创建了一个模型方法:

def self.posts_for_users_groups(current_user)
  includes(:groups => :users).where('users.id' => current_user.id)
end

我从家里的控制器打来电话:

def index
  @user_visible_posts = Post.posts_for_users_groups(current_user)
end

再次感谢@shioyama:D