我试图找出处理存储连接表中相同对象数量的字段的最佳方法。
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
时:
Connection
ConnectorType
Connection
存在ConnectorType
,则Connection#number
应增加当我从ConnectorType
Element
时
Connection#number
应该减少。Connection#number == 0
删除Connection
我是rails的新手我不知道Rails的方法:
答案 0 :(得分:2)
如果我理解的是,您希望监视给定元素与给定connector_type之间的连接数,但您不希望数据库中有重复的Connection对象?
您可以使用回调(代码未测试)
# 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
将触发创建新连接,如果已经有一个链接此元素和此连接器类型...