上创建的ActiveRecord的重写ID重写、ActiveRecord、ID

2023-09-09 21:58:46 作者:祭奠№嶒經

有什么办法上建立覆盖模型的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,这就是为什么你不能使用大规模分配进行设置。但是,手动设置的时候,它只是作品:

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允许您使用同一个belongs_to的语义ActiveRecord的,但不是在迁移和创建表,并招致数据库的开销对每一个电话,你只是你的数据存储在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.