ArgumentError: wrong number of arguments (1 for 2)

情到浓时终转凉″ 提交于 2020-01-11 04:46:09

问题


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:

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:

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:

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?


回答1:


update_column takes two arguments. You are only passing one.

Instead of:

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

Try:

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

This may seem like two arguments:

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

but it's actually one hash.

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

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



回答2:


As Mischa pointed out, update_column takes 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:

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


来源:https://stackoverflow.com/questions/8813957/argumenterror-wrong-number-of-arguments-1-for-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!