0

私の Rails アプリには has_many_through リレーションがあります。結合モデル/テーブルを使用して、関係に関するデータを保存したいと考えています (具体的には、特定の関係が使用された回数)。

サブジェクトとの既存の関係をチェックし、存在する場合は関係のカウンターを更新し、存在しない場合は作成するクラスの1つに追加メソッドを作成しています。

例:

CoffeeDrinker は、Coffee through Cup に関連しています。CoffeeDrinker が一口飲むたびに、その特定の Cup のカウンターをインクリメントする必要があります。CoffeeDrinker が初めて一口飲むと、Cup が作成され、カウンターが初期化されます。

リレーション オブジェクトを保持するための最も簡単かつ/または最も正しい方法は何ですか?

4

1 に答える 1

1

私はあなたの質問を理解していないか、これがどれほど明白であるかに驚くでしょう。関係を次のように定義します。

#coffee_drinker.rb
has_many :cups
has_many :coffees, :through => :cup

#cup.rb
belongs_to :coffee
belongs_to :coffee_drinker

#coffee.rb
has_many :cups
has_many :coffee_drinkers, :through => :cup

coffee_drinker.cups
coffee_drinker.coffees

coffee.cups
coffee.coffee_drinkers

#coffee_drinker.rb
after_save :update_cups_drunk

def update_cups_drunk
  cups.find_by_coffee_id(coffee_id).increment!(:count)
end

#maybe you don't have access to the coffee_id

def update_cups_drunk
  cups.find_by_coffee_id(coffees.last.id).increment!(:count)
end
于 2010-08-22T09:13:10.200 に答える