我想弄清楚处理存储在我的连接表中同一对象的数量的字段的最佳方式。has_many通过和其他数据:计数
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
当我添加一个ConnectorType
到Element
:
- 如果没有这个
ConnectorType
- 如果这
ConnectorType
一个Connection
存在一个Connection
必须创建,Connection#number
应该是增量
当我删除ConnectorType
从Element
:
Connection#number
应递减。- 如果
Connection#number == 0
删除Connection
我新的轨道,我不知道Rails的方式做到这一点:
- 回调
- 转储号码字段和存储为重复的行在连接模型中。
- ...
你想要你的回调做什么?你有很多的选项http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html你有没有研究过has_and_belongs_to_many的联合关系? – 2011-01-11 13:11:41