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
时:
- A <如果不存在此
ConnectorType
,则必须创建 code>Connection - 如果存在此
ConnectorType
的Connection
,则Connection#number
应该递增
当我从 Element
中删除 ConnectorType
时:
Connection#number
应该递减。- 如果
Connection#number == 0
删除Connection
我是 Rails 新手,我不知道 Rails 执行此操作的方法:
- 回调
- 转储数字字段并存储为重复项连接模型中的行。
- ...
I am trying to figure out the best way to handle a field storing the quantity of the same object in my join table.
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
When I add a ConnectorType
to an Element
:
- A
Connection
must be created if there isn't for thisConnectorType
- If a
Connection
for thisConnectorType
exists,Connection#number
should be increment
When I remove a ConnectorType
from an Element
:
Connection#number
should be decrement.- If
Connection#number == 0
delete theConnection
I am new to rails I don't know the Rails way to do this :
- Callback
- Dump the number field and store as duplicate rows in the join model.
- ...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我理解得很好,您想要监视给定元素和给定connector_type之间的连接数,但您不希望数据库中存在重复的Connection对象?
您可以为此使用回调(代码未测试)
但是,我不确定通过这样的 has_many 关系向元素添加connector_type
是否会触发新连接的创建,如果已经有一个链接该元素并且该连接器类型...
If I understand well, you want to monitor the number of connections between a given element and a given connector_type, but you do not want to have duplicate Connection objects in your database?
You can use callbacks for this (code not tested)
However, I'm not sure that adding a connector_type to an element via the has_many relation like this:
will trigger the creation of a new connection, if there already is one linking this element and this connector type...