Rails:如何将值设置为“id”列,而不是主键

时间:2017-03-17 19:22:26

标签: sql ruby-on-rails postgresql

我想在我的表中手动将值设置为字段“ID”,而不是主键。每次我使用.id属性并为其赋值时,它都会被分配给主键(abc_id)而不是“id”

table/model: MyModel
primary key: abc_id
another column: id

我尝试了以下保存ID的方法,但似乎都没有。

test = MyModel.new
test.id = 555 
==> updates abc_id
test.write_attribute(:id, 555)
 ==> private method not available
test.update_attribute(:id,555)
==> updates abc_id -->ActiveRecord::StatementInvalid: PG::NotNullViolation: ERROR:  null value in column "id" violates not-null constraint
test.attributes = {id: 555} 
==> no error but doesn't do anything
test.send(:attributes=, id: 555) 
==> saves other attributes but not id
 => nil 

如何为“id”分配值,因为我在尝试保存记录时总是出现PG::NotNullViolation: ERROR: null value in column "id" violates not-null constraint错误

1 个答案:

答案 0 :(得分:0)

这个答案有帮助吗?

How to set primary key in ruby on rails migration?

根据我的经验,这不应该是必要的。