1

ユーザーがいるとしましょう。

ユーザーは、このようにアカウントを通じて has_many のドキュメントを持っています…</p>

class User < ActiveRecord::Base
  belongs_to :account
  has_many :documents, :through => :account, :order => "created_at DESC"
end

class Account < ActiveRecord::Base
  has_one :owner, :class_name => "User", :dependent => :destroy
  has_many :documents, :dependent => :destroy
end

class Document < ActiveRecord::Base
  belongs_to :account
end

素晴らしくシンプルですが、ここが難しいところです…</p>

ユーザーは、共同作業者の結合テーブルを介してドキュメントで共同作業することもできます…</p>

class Collaborator < ActiveRecord::Base
  belongs_to :user
  belongs_to :documnet
end

class Document < ActiveRecord::Base
  has_many :collaborators, :dependent => :destroy
  has_many :users, :through => :collaborators
  accepts_nested_attributes_for :collaborators, :allow_destroy => true
end

これの最後のユーザービットは、私がよくわからないものです。別のドキュメントを追加したいのですが、user.documents を呼び出すと、アカウントを介して両方のドキュメントと共同作業しているドキュメントがブレンドされます…</p>

class User < ActiveRecord::Base
  belongs_to :account
  has_many :documents, :through => :account, :order => "created_at DESC"

  #documents need to do both has manys…
  has_many :collaborators, :dependent => :destroy
  has_many :documents, :through => :collaborators
end

ありがとう、それは少し長いですが、きちんとした解決策を考えることができます。どんな助けでも大歓迎です。

4

1 に答える 1

3

テーブルdocumentsでリクエストするメソッドを作成し、ユーザーに関連するドキュメントを見つけることができますaccountscollaborators

class User < ActiveRecord::Base

  #...

  def documents
    Document.includes(:account, :collaborators).where('collaborators.user_id = ? OR documents.account_id = ?', self.id, self.account.id)
  end

end

私はこのリクエストをテストしていませんが、理解していただければ幸いです。間違っていたら訂正してください。

2 については、has_many documents, :through...不要になった場合は削除できます。それ以外の場合は、別の名前を付ける必要があります (上記の方法とは異なります)。

于 2013-07-06T15:30:22.187 に答える