3

我正在使用可用的指南/api/书籍自学 Rails,但我无法理解与三路/嵌套 has_many 的连接:通过关联。

我有用户连接:通过会员资格

我也有一个多对多组的帖子。同一个帖子可以发布到多个群组 + 群组可以有多个帖子。

我希望能够为用户的主页显示用户所属的所有不同帖子

例如。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

路线.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#index

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

4

2 回答 2

1

我相信这就是你想要的:

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

这将生成这样的 SQL(for 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(不完全相同,但相似)

于 2012-12-10T15:38:37.177 回答
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

于 2012-12-11T02:56:58.643 回答