1

我在用着:

ranking = Ranking.create()
ranking.send("#{month}=", rank)
ranking.save!

我想附加#{month}列中的任何值,而不是替换它。例如,如果我正在执行:

month = 'january'

ranking.send("#{month}=", 500)
ranking.save!

稍后再一次:

month = 'january'

ranking.send("#{month}=", 250)
ranking.save!

该特定排名的列值january应为 750。

这可以用当前的 ActiveRecord API 实现吗?

4

1 回答 1

1

你可以通过增量来做到这一点!方法

month = 'january'
ranking.increment!(month, 250)

更新:

证明评论问题(例如月份='一月'):

irb(main):011:0> p.increment!(month, 70)
   (0.0ms)  begin transaction
  SQL (0.0ms)  UPDATE "products" SET "jan" = ?, "updated_at" = ? WHERE "product
"."id" = 1  [["jan", 171], ["updated_at", Sun, 06 Oct 2013 04:23:54 UTC +00:00]

   (0.0ms)  commit transaction
=> true
irb(main):012:0> p
=> #<Product id: 1, name: nil, description: nil, jan: 171, created_at: "2013-10-
06 04:22:50", updated_at: "2013-10-06 04:23:54">

和另一个案例

irb(main):013:0> p.increment!("#{month}", 70)
   (0.0ms)  begin transaction
  SQL (0.0ms)  UPDATE "products" SET "jan" = ?, "updated_at" = ? WHERE "products
"."id" = 1  [["jan", 241], ["updated_at", Sun, 06 Oct 2013 04:24:10 UTC +00:00]]

   (0.0ms)  commit transaction
=> true
irb(main):014:0> p
=> #<Product id: 1, name: nil, description: nil, jan: 241, created_at: "2013-10-
06 04:22:50", updated_at: "2013-10-06 04:24:10">
于 2013-10-06T03:55:43.163 回答