在 ActiveRecord 中创建时覆盖 id [英] Overriding id on create in ActiveRecord

查看:21
本文介绍了在 ActiveRecord 中创建时覆盖 id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在创建时覆盖模型的 id 值?类似的东西:

Is there any way of overriding a model's id value on create? Something like:

Post.create(:id => 10, :title => 'Test')

会很理想,但显然行不通.

would be ideal, but obviously won't work.

推荐答案

id 只是 attr_protected,这就是为什么你不能使用 mass-assignment 来设置它.但是,手动设置时,它就起作用了:

id is just attr_protected, which is why you can't use mass-assignment to set it. However, when setting it manually, it just works:

o = SomeObject.new
o.id = 8888
o.save!
o.reload.id # => 8888

我不确定最初的动机是什么,但我在将 ActiveHash 模型转换为 ActiveRecord 时这样做了.ActiveHash 允许您在 ActiveRecord 中使用相同的belongs_to 语义,但无需迁移和创建表,并在每次调用时产生数据库开销,您只需将数据存储在 yml 文件中.数据库中的外键引用 yml 中的内存 id.

I'm not sure what the original motivation was, but I do this when converting ActiveHash models to ActiveRecord. ActiveHash allows you to use the same belongs_to semantics in ActiveRecord, but instead of having a migration and creating a table, and incurring the overhead of the database on every call, you just store your data in yml files. The foreign keys in the database reference the in-memory ids in the yml.

ActiveHash 非常适合不经常更改且仅由开发人员更改的选项列表和小表.因此,当从 ActiveHash 到 ActiveRecord 时,最简单的方法是保持所有外键引用相同.

ActiveHash is great for picklists and small tables that change infrequently and only change by developers. So when going from ActiveHash to ActiveRecord, it's easiest to just keep all of the foreign key references the same.

这篇关于在 ActiveRecord 中创建时覆盖 id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆