在 Rails Scaffolding 中添加自动增量 SNO 列?

发布于 2024-08-02 18:34:14 字数 74 浏览 3 评论 0原文

有没有一种方法可以通过 Rails 中的脚手架创建序列号 (SNO) 列,该序列号在添加记录时增加,在删除记录时减少并且无法手动修改?

Is there a way in which I can create a serial number (SNO) column through scaffolding in Rails which increases on adding a record, decreases on deleting a record and cannot be modified manually?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

请恋爱 2024-08-09 18:34:14

目前尚不清楚是否涉及任何关系,但听起来 counter_cache 可能是一个不错的选择。

Railscast 剧集 提供了代码示例和视频教程。

It's not clear whether there is any relationship involved, but it sounds like counter_cache may be a good fit.

A Railscast episode provides the code examples and a video tutorial.

过期以后 2024-08-09 18:34:14

如果您想在模型上创建摘要列,您需要将此逻辑放入模型中。没有为此的内置方法(如标准自动增量字段),但可以轻松添加:

class Parent << ActiveRecord::Base 
    # Contains a field: summary_field
end 


class Child << ActiveRecord::Base

   after_save => :increment_summary
   before_destroy => :decrement_summary

   def increment_summary
        Parent.find(self.id).summary_field.increment
   end 

   def decrement_summary
        Parent.find(self.id).summary_field.decrement
   end 

end 

If you want to create a summary column on a model you will need to put this logic into your models. There is not a built in method for this (like a standard autoincrement field), but it can be added easily:

class Parent << ActiveRecord::Base 
    # Contains a field: summary_field
end 


class Child << ActiveRecord::Base

   after_save => :increment_summary
   before_destroy => :decrement_summary

   def increment_summary
        Parent.find(self.id).summary_field.increment
   end 

   def decrement_summary
        Parent.find(self.id).summary_field.decrement
   end 

end 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文