В рельсах, как я могу создать объединенное отношение между двумя has_many: через отношения - PullRequest
0 голосов
/ 03 февраля 2011

У меня есть набор моделей Active Record, настроенный так:

Account
  has_many :account_groups
  has_many :groups, :through => :account_groups

Posts
  has_many :post_groups
  has_many :groups, :through => :post_groups

Это конфигурация безопасности, и мне нужно иметь возможность запрашивать сообщения, принадлежащие группе, к которой у учетной записи есть доступ .... поэтому я бы хотел сказать:

@account.posts

И получите отфильтрованный запрос сообщений, принадлежащих группам, которые перекрывают группы, к которым у учетной записи есть доступ ... но я не могу понять правильный синтаксис.

Помощь.

Для пояснения, SQL, который я ищу, будет выглядеть так:

SELECT DISTINCT posts.* FROM accounts
    JOIN account_groups ON account_groups.account_id = accounts.id
    JOIN groups ON groups.id = account_groups.group_id
    JOIN post_groups ON post_groups.group_id = groups.id
    JOIN posts ON posts.id = post_groups.post_id
    WHERE accounts.id = 2

Мне бы очень хотелось, чтобы это была именованная область или отношение, а не только искатель sql.

1 Ответ

1 голос
/ 03 февраля 2011

Ближайшее, что я мог получить:

class Account < ActiveRecord::Base
  def posts
    Post.includes(:post_groups => [:group => [:account_groups => :account]]).where('account_groups.account_id = ?',1)
  end
end

Возможно, вы могли бы извлечь его из области видимости, вместо:

class Post < ActiveRecord::Base
  has_many :post_groups
  has_many :groups, :through => :post_groups

  scope :for_account, lambda {|account| joins(:post_groups => [:group => [:account_groups => :account]]).where('account_groups.account_id = ?',account.id)}
end

Оба результата:

SELECT "posts".* FROM "posts" INNER JOIN "post_groups" ON "post_groups"."post_id" = "posts"."id" INNER JOIN "groups" ON "groups"."id" = "post_groups"."group_id" INNER JOIN "account_groups" ON "account_groups"."group_id" = "groups"."id" INNER JOIN "accounts" ON "accounts"."id" = "account_groups"."account_id" WHERE (account_groups.account_id = 1)

Оба из них ... требуют, чтобы PostGroup принадлежал_to: group и group has_many account_groups

...