Rails 4 update_all语法 - 参数错误

时间:2016-06-22 18:59:15

标签: ruby-on-rails-4 arguments rails-activerecord update-all

我收到了错误:

  

参数数量错误(2对1)

在我定义我的方法以更新所有任务状态时,在我的Task模型上。什么是正确的语法?

class Task < ActiveRecord::Base
  belongs_to :user

  def self.toggle(user, groups)
    groups.each do |status, ids|
      user.tasks.update_all({status: status.to_s}, {id: ids}) #=> error here
    end
  end
end

class GroupIdsByStatus
  def self.group(options = {})
    result = Hash.new {|h,k| h[k] = []} 
    options.reduce(result) do |buffer, (id, status)| 
      buffer[status.to_sym] << id
      buffer
    end
    result
  end
end

class TasksController < ApplicationController
  def toggle
    groups = GroupIdsByStatus.group(params[:tasks])
    Task.toggle(current_user, groups)

    redirect_to tasks_path
  end
end

1 个答案:

答案 0 :(得分:1)

方法update_all接收单个Hash作为其唯一参数。您需要将所有更新放入单个参数中:

user.tasks.update_all(status: status.to_s, id: ids)

# The above line of code is identical to:
# user.tasks.update_all( {status: status.to_s, id: ids} )  # < Notice the curly braces

有关此方法的更多信息显示在Rails Relation Docs