使用 rails 更新由复合键标识的对象
Update object identified by composite key with rails
我实际上有一个 table 组件。每个组件都有一个特定的版本,就像上面描述的那样(还有其他属性,如名称、component_type_id、...):
编号 | version_id
-----+------------
167 | 1
167 | 96
167 | 97
167 | 98
167 | 99
166 | 1
166 | 92
属性"id"和"version_id"是一个复合主键,我想通过识别这个复合主键来编辑一个对象
如果我想更新组件的版本 99 #167 =>
当我使用 rails 时:
Component.where(id: 167, version_id: 99).first.update({"component_type_id"=>"5", "name"=>"CCC"})
Rails 这样做:
SELECT "components".* FROM "components" WHERE "components"."id" = AND "components"."version_id" = ORDER BY "components"."id" ASC LIMIT 1 [["id", 167], ["version_id", 99]]
UPDATE "components" SET "name" = , "updated_at" = WHERE "components"."id" = 167 [["name", "CCC"], ["updated_at", "2016-04-19 08:05:09.049345"]]
但我想要这样的东西:
UPDATE "components" SET "name" = , "updated_at" = WHERE "components"."id" = 167 AND version_id = 99 [["name", "CCC"], ["updated_at", "2016-04-19 08:05:09.049345"]]
感谢帮助我
干杯
由于这些只是具有给定 ID 和版本的一条记录,尝试:
Component.where(id: 167, version_id: 99).update_all(component_type_id: 5, name: "CCC")
这样,Rails不会实例化一条记录,避免你的问题。
我实际上有一个 table 组件。每个组件都有一个特定的版本,就像上面描述的那样(还有其他属性,如名称、component_type_id、...):
编号 | version_id
-----+------------
167 | 1
167 | 96
167 | 97
167 | 98
167 | 99
166 | 1
166 | 92
属性"id"和"version_id"是一个复合主键,我想通过识别这个复合主键来编辑一个对象
如果我想更新组件的版本 99 #167 =>
当我使用 rails 时:
Component.where(id: 167, version_id: 99).first.update({"component_type_id"=>"5", "name"=>"CCC"})
Rails 这样做:
SELECT "components".* FROM "components" WHERE "components"."id" = AND "components"."version_id" = ORDER BY "components"."id" ASC LIMIT 1 [["id", 167], ["version_id", 99]]
UPDATE "components" SET "name" = , "updated_at" = WHERE "components"."id" = 167 [["name", "CCC"], ["updated_at", "2016-04-19 08:05:09.049345"]]
但我想要这样的东西:
UPDATE "components" SET "name" = , "updated_at" = WHERE "components"."id" = 167 AND version_id = 99 [["name", "CCC"], ["updated_at", "2016-04-19 08:05:09.049345"]]
感谢帮助我 干杯
由于这些只是具有给定 ID 和版本的一条记录,尝试:
Component.where(id: 167, version_id: 99).update_all(component_type_id: 5, name: "CCC")
这样,Rails不会实例化一条记录,避免你的问题。