Rails 4 update_all 语法 - 参数错误
Rails 4 update_all syntax - Argument error
我遇到错误:
Wrong number of arguments (2 for 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
方法 update_all
接收单个哈希作为其唯一参数。您需要将所有更新放入单个参数中:
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
我遇到错误:
Wrong number of arguments (2 for 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
方法 update_all
接收单个哈希作为其唯一参数。您需要将所有更新放入单个参数中:
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