ruby-on-rails - rails : Scoped ID in addition to primary id

标签 ruby-on-rails scope

假设我有很多博客,每个博客都有has_many个帖子。它们存储在两个表中(“博客”和“帖子”)。是否可以向博客表中添加一个附加列(例如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 递减。

最佳答案

您最好的选择是在博客上保留上次使用的 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

或者类似的爵士乐。

如果保存失败,计数器将不会增加,因为这一切都在一次巨大的交易中(就像完全是企业)。

关于ruby-on-rails - rails : Scoped ID in addition to primary id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1361123/

相关文章:

ruby-on-rails - 将制表符分隔的 CSV 文件解析为 Ruby 2.0 中的哈希数组

ruby-on-rails - 为什么 "rails generate migration"调用 "invoke activerecord"

javascript - 在函数作用域内声明的变量会导致 if 语句出错

javascript - 如何深入理解Javascript的var作用域和闭包?

javascript - 从父函数中检索函数参数

ruby-on-rails - 无法通过在 Rails 应用程序中运行 Ruby 打开本地主机

ruby-on-rails - Mongoid::Document 是 GlobalID::ActiveJobs 的标识吗?

ruby-on-rails - Rspec 中的动态期望

ruby - Ruby 循环中的常量和作用域

java - Struts 2 如何显示 map 复选框列表