0

1) ユーザーは多くの原因を持つことができ、原因は多くのユーザーに属することができます。

2) ユーザーは多くのキャンペーンを持つことができ、キャンペーンは多くのユーザーに属することができます。キャンペーンは 1 つの原因に属します。

原因やキャンペーンを特定のユーザーに個別に割り当てることができるようにしたいと考えています。したがって、ユーザーに特定のキャンペーンを割り当てることができます。または、ユーザーに原因を割り当て、その原因のすべてのキャンペーンをユーザーに関連付ける必要があります。

それは可能ですか?そして、関係を次のように単純化できるように設定できますか。

User.causes = ユーザーに属するすべての原因

User.campaigns = 原因の関連付けまたはキャンペーンの関連付けを通じてユーザーに属するすべてのキャンペーン

4

3 に答える 3

1

これはうまくいくはずです。

class User < ActiveRecord::Base
  has_many :causes, :through => :cause_users
  has_many :campaigns, :through => :campaign_users
  # other model stuff

class Cause < ActiveRecord::Base
  has_many :users, :through => :cause_users
  has-many :campaigns
  # other model stuff

class Campaign < ActiveRecord::Base
  belongs_to :cause
  has_many :users, :through => :campaign_users
  # other model stuff

class CampaignUser < ActiveRecord::Base
  belongs_to :campaign
  belongs_to :user
  # other model stuff

class CauseUser < ActiveRecord::Base
  belongs_to :cause
  belongs_to :user
  # other model stuff

has_many :through では、示されているように、campaign_users と cause_users の結合ごとに新しいモデルを作成する必要がありますが、後で has_and_belongs_to_many よりも多くの機能を提供します。

また、:campaign_users や :cause_users よりも適切な名前を使用して、関係がより意味のあるものにすることをお勧めします。

于 2010-04-30T16:43:38.240 に答える
0

:has_many :through は、結合モデルを使用してユーザーとキャンペーンの間で関連付けを行うことができ、別の結合モデルを使用してユーザーと原因の間で関連付けを行うこともできます。原因モデルに :has_many :campaigns 関連付けを作成し、キャンペーン モデルに :belongs_to :cause を配置できます。

ただし、User.campaigns.orders または User.order.campaigns ですべてのユーザー キャンペーンまたは原因を取得することはできません。User.campaigns コレクションまたは User.causes を反復処理して、Campaign.cause または Cause.capaigns を取得する必要があります。または、結合と条件を使用して結合内の情報をフィルタリングして、カスタム SQL クエリを作成することもできます。

于 2010-04-30T16:55:58.443 に答える
0

以下を使用する必要があると思います。

class User < ActiveRecord::Base
   has_and_belongs_to_many :causes
   has_and_belongs_to_many :campaigns
end

class Cause < ActiveRecord::Base
   has_and_belongs_to_many :users
   has_many :campaigns
end

class Campaign < ActiveRecord::Base
   has_and_belongs_to_many :users
   belongs_to :cause
end

このように使用できます

User.causes
User.campaigns

Cause.campaing
Cause.users

Campaign.users
Campaign.cause

関係についてはこちら、についてはこちら、についてはこちらで読むことができます。has_and_belongs_to_manyhas_onebelongs_to

これがあなたが望むものかどうか教えてください:]

編集:

「User.campaigns は、ユーザーの原因からのキャンペーン、またはユーザーに関連付けられた個々のキャンペーンである必要があります」

すべてのキャンペーンを返すユーザー モデルのメソッドを使用できます。このようなもの:

def all_campaigns
   self.campaigns + self.causes.collect{ |c| c.campaigns }
end
于 2010-04-30T16:42:22.970 に答える