Ruby-on-rails ArgumentError:参数数量错误(1 对 2)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8813957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:36:11  来源:igfitidea点击:

ArgumentError: wrong number of arguments (1 for 2)

ruby-on-railsrubyroutingcrud

提问by airplaneman19

I'm very new to Rails, MVC, and CRUD, and I'm trying to use the update method to change the amount of votes on a post. I have the following code in my Posts Controller update method:

我对 Rails、MVC 和 CRUD 非常陌生,我正在尝试使用 update 方法来更改帖子的投票数量。我的 Posts Controller 更新方法中有以下代码:

def update
    @post = Post.find(params[:id])

    if params[:vote] == 'up'
        @post.update_column(:ups => @post[:ups] + 1)
    elsif params[:vote] == 'down'
        @post.update_column(:downs => @post[:downs] + 1)
    end

    flash[:notice] = "Thanks for voting! This helps us determine important issues in our schools."

    redirect_to 'Posts#index'
end

and I have the following code in my routes.rb:

我的routes.rb中有以下代码:

OpenMCJC::Application.routes.draw do
  root :to => 'posts#index'
  resources :posts
  match '/posts/:id/:vote', :to => 'posts#update'
end

After navigating to "/posts/3/up", it throws the following error:

导航到“/posts/3/up”后,它抛出以下错误:

ArgumentError in PostsController#update

wrong number of arguments (1 for 2)

The request parameters according to the page are as such:

根据页面的请求参数如下:

{"id"=>"3",
"vote"=>"up"}

Can you help me figure out what went wrong?

你能帮我弄清楚出了什么问题吗?

回答by Mischa

update_columntakes two arguments. You are only passing one.

update_column需要两个参数。你只是通过了一个。

Instead of:

代替:

@post.update_column(:ups => @post[:ups] + 1)

Try:

尝试:

@post.update_column(:ups, @post[:ups] + 1)

This may seem like twoarguments:

这似乎是两个论点:

:ups => @post[:ups] + 1

but it's actually onehash.

但它实际上是一个哈希值。

With the more commonly used update_attributes, you can pass a hash:

使用更常用的update_attributes,您可以传递散列:

@post.update_attributes(:ups => @post[:ups] + 1)

回答by Peter Brown

As Mischa pointed out, update_columntakes two arguments. However, I would discourage you from using this method. First, it skips validations which may not be what you want. Second, Rails has built-in methods for incrementing or decrementing values. In your case, you could change your controller method to something like this:

正如米沙指出的那样,update_column需要两个论点。但是,我不鼓励您使用这种方法。首先,它会跳过可能不是您想要的验证。其次,Rails 具有用于递增或递减值的内置方法。在您的情况下,您可以将控制器方法更改为如下所示:

if params[:vote] == 'up'
  @post.increment(:ups)
elsif params[:vote] == 'down'
  @post.increment(:downs)
end