2011-01-11 59 views
1

我想弄清楚处理存储在我的连接表中同一对象的数量的字段的最佳方式。has_many通过和其他数据:计数

Schema

class Element < ActiveRecord::Base 
    has_many :connections 
    has_many :connector_types, :through => :connections 
end 

class ConnectorType < ActiveRecord::Base 
    has_many :connections 
    has_many :elements, :through => :connections 
end 

class Connection < ActiveRecord::Base 
    belongs_to :element 
    belongs_to :connector_type 
end 

当我添加一个ConnectorTypeElement

  • 如果没有这个ConnectorType
  • 如果这ConnectorType一个Connection存在一个Connection必须创建,Connection#number应该是增量

当我删除ConnectorTypeElement

  • Connection#number应递减。
  • 如果Connection#number == 0删除Connection

我新的轨道,我不知道Rails的方式做到这一点:

  • 回调
  • 转储号码字段和存储为重复的行在连接模型中。
  • ...
+0

你想要你的回调做什么?你有很多的选项http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html你有没有研究过has_and_belongs_to_many的联合关系? – 2011-01-11 13:11:41

回答

2

如果我没有理解好了,你想监控一个给定的元素和给定connector_type之间的连接数,但你不想在你的数据库中有重复连接对象?

您可以使用此回调(未测试的代码)

# connection.rb 
before_create :bc_callback 
before_destroy :bd_callback 


private 
def before_create 
    if (existing_connection = self.find_by_element_id_and_connector_type_id(element_id, connector_type_id)) 
    existing_connection.number++ 
    existing_connection.save 
    return false # Do not create a new connection object 
    end 
end 

def before_destroy 
    number-- 
    # If you still have 1 connection or more, the object won't be destroyed 
    if (number > 0) 
    save 
    return false 
    end 
end 

但是,我不知道该通过的has_many关系这样添加connector_type到一个元素:

@element.connector_types << @connector_type 

将触发创建一个新的连接,如果已经有一个链接这个元素和这个连接器类型...

+0

这就是我想要的,但是当我在我的before_create回调中返回false以避免创建对象时,得到了一个ActiveRecord :: RecordNotSaved – 2011-01-12 13:21:15