假设我有很多博客,每个博客都有has_many帖子。它们存储在两个表中(“博客”和“帖子”)。是否可以向存储ID的博客表中添加额外的列(例如,scoped_id),该ID的范围由博客确定。
示例
Blog: 1
- Posts
- id: 1, scoped_id: 1
- id: 2, scoped_id: 2
- id: 3, scoped_id: 3
Blog: 2
- Posts
- id: 4, scoped_id: 1
- id: 5, scoped_id: 2
- id: 6, scoped_id: 3我知道counter_cache可以跟踪父博客的帖子数量。但是,如果一个帖子被销毁,我不希望scoped_id减少。
发布于 2009-09-01 12:30:00
最好的办法是将上次使用的ID保留在博客上,并通过以下方式填充它:
class Post < ActiveRecord::Base
…
before_create :populate_scoped_id
def populate_scoped_id
blog.increment!(:latest_scoped_post_id)
self[:scoped_id] = blog.latest_scoped_post_id
end
…
end或者像这样的爵士音乐。
如果保存失败,计数器将不会递增,因为它都在一个巨大的事务中(就像,完全是企业事务)。
发布于 2009-09-01 08:57:52
是的,您绝对可以添加其他列,如果是我,我会执行before_save回调来保存scoped_id,如果它是new_record?
class Post < ActiveRecord::Base
...
before_save :populate_scoped_id
def populate_scoped_id
assign_the_scoped_id_method if self.new_record?
end
...
end希望这会有帮助=)
https://stackoverflow.com/questions/1361123
复制相似问题