1

I'm getting the error:

Wrong number of arguments (2 for 1)

On my Task model when I defined my method to update all status of tasks. What is the correct syntax?

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
Wes Foster
  • 8,770
  • 5
  • 42
  • 62

1 Answers1

1

The method update_all receives a single Hash as its sole argument. You need to put all of the updates into the single argument:

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

More information on this method is shown in the Rails Relation Docs

Wes Foster
  • 8,770
  • 5
  • 42
  • 62
  • I did that, but now It's showing another error: ActiveRecord::StatementInvalid in TasksController#toggle SQLite3::MismatchException: datatype mismatch: UPDATE "tasks" SET "status" = 'done', "id" = NULL WHERE "tasks"."user_id" = ? – Bruno Henrique Jun 22 '16 at 20:35
  • That is the correct syntax, so the problem is solved. The *new* problem is caused by the `ids` variable being `NULL`. You'll want to ensure that `ids` is not `NULL` to prevent getting that error. – Wes Foster Jun 22 '16 at 20:37