【问题标题】:Use update_columns on an hstore attribute在 hstore 属性上使用 update_columns
【发布时间】:2015-07-06 00:20:10
【问题描述】:

rails 4 中的hstore 属性是否有等效的update_columns

我的模型是:

class Image < ActiveRecord::Base
  store_accessor :additions, :small, :medium, :big, :image_version
end

假设我想更新small
我试过了:

@image = Image.first
@image.update_columns(small: 'my_small_image')

但我当然会收到:

PG::UndefinedColumn: ERROR:  column "small" of relation "contents" does not exist
LINE 1: UPDATE "images" SET "small" = 'my_small_image' WHERE "imag...
                              ^
: UPDATE "images" SET "small" = 'my_small_image' WHERE "images"."id" = 1

有简单的方法吗?

编辑:我不能使用update_attributes,因为我需要保存传递的参数。

update_attributes 调用save,我不想要这个,因为它保存了所有其他更改的属性,而不仅仅是通过的那个。

例子:

@image = Image.first
@image.big = 'fjdiosjfoa'
@image.update_attributes(small: 'my_small_image')

大大小小的都得救了。

相反,使用update_columns,只能保存一小部分。如何用 hstore 做到这一点?

【问题讨论】:

    标签: ruby-on-rails ruby postgresql ruby-on-rails-4 hstore


    【解决方案1】:

    如果要保存,请使用update_attributes(small: 'my_small_image')

    如果您不想保存,请使用assign_attributes(small: 'my_small_image')

    【讨论】:

    • 嗯我需要使用update_columns 而不是update_attributes,因为第二个调用save。我在我的问题中添加了一些细节。
    • assign_attributes 对你没有帮助吗?
    • 不...这有点难以解释。看看我的问题中的例子。
    • 我明白了。感谢您的宝贵时间
    【解决方案2】:

    使用 update_column 但传入 hstore 属性和哈希。为了防止任何现有的 hstore 值被吹走,您需要合并现有值:

    @image.update_column(:additions, @image.additions.merge({ 'small' => 'my_small_image' }) )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-23
      • 1970-01-01
      相关资源
      最近更新 更多