0

在我的 Rails 应用程序中,我有一个 has_many_through 关系。我想使用连接模型/表来存储有关关系的一些数据(具体来说,使用该特定关系的次数)。

我正在我的一个类上编写一个 add-method,它应该检查与主题的任何现有关系,如果存在则更新关系上的计数器,如果不存在则创建它。

例子:

CoffeeDrinker 与 Coffee through Cup 有关。每次 CoffeeDrinker 喝一口时,该特定杯子上的计数器都会增加。CoffeeDrinker 第一次喝一口时,应该创建杯子并初始化计数器。

获取关系对象的最简单和/或最正确的方法是什么?

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 回答