【问题标题】:Method missing update_attribute方法缺少 update_attribute
【发布时间】:2014-05-20 21:27:52
【问题描述】:

我有三个模型:

  1. 商店 (has_many :products)
  2. 产品(has_many :product_fieldsbelongs_to :store
  3. Product_fields(有一个belongs_to :product

我正在使用 Sidekiq 更新 product_fields 中名为 content 的列(当我创建模型时,我在名为 second_content 的同一模型中的列中插入了一个 url,因此原始内容列在创建时为空,但随后我我正在尝试将我的工作人员中的内容列更新为新值。这是我的工作人员:

def perform(store_id)
   store = Store.find(store_id)

   store.products.each do |product|
      if product.type_of == "Video"
        video_url = URI.parse product.product_fields[0].second_content
        video = open("LINK HERE").read
        video = ActiveSupport::JSON.decode video

        product.product_fields[0].update_attribute(:content, video)
      end
   end
end

我的控制器的创建操作如下所示:

def create
   @store = Store.new(store_params)
   respond_to do |format|
      if @store.save

          #Start video job
          VideosWorker.perform_async(@store.id)

          format.html { redirect_to @store, notice: 'Store was successfully created.' }
      end
   end
end

一切似乎都在工作,除了在 Sidekiq 终端我得到错误:

undefined method `update_attribute' for #<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_ProductField:0x0000010531bdd8>

【问题讨论】:

  • 尝试使用product.product_fields.first.update_attribute(:content, video) 你不能在collection_proxy 上调用update_attribute
  • @bjhaid,感谢您的回复,但现在我收到错误消息:can't cast Hash to text
  • video 是一个哈希值,应该是一个字符串,这就是你得到那个错误的原因
  • @bjhaid,谢谢。您可以添加您的答案以便我接受吗?

标签: ruby-on-rails ruby background-process sidekiq


【解决方案1】:

用途:

product.product_fields.first.update_attribute(:content, video)

代替:

product.product_fields[0].update_attribute(:content, video)

因为您不能在 CollectionProxy 对象上调用 update_attribute,所以还要确保 video 是一个字符串

【讨论】:

    猜你喜欢
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-25
    相关资源
    最近更新 更多