2012-01-11 121 views
7

我對Rails,MVC和CRUD非常陌生,我試圖使用update方法來更改帖子上的投票數量。我在我的帖子控制器更新方法如下代碼:ArgumentError:錯誤的參數數量(1爲2)

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 

,我有我的routes.rb中下面的代碼:

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

導航到「/職位/ 3 /向上」後,它引發以下錯誤:根據頁面

ArgumentError in PostsController#update 

wrong number of arguments (1 for 2) 

請求參數爲這樣:

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

你能幫我弄清楚出了什麼問題嗎?

回答

14

update_column需要兩個參數。你只能通過一個。

相反的:

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

嘗試:

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

這似乎是參數:

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

但它實際上是一個哈希

與更常用update_attributes,你可以傳遞一個哈希:

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

這已經咬了我之前。可悲的是。 – courtsimas 2017-05-11 06:07:35

7

由於米沙指出,update_column有兩個參數。不過,我會勸阻你不要使用這種方法。首先,它跳過可能不是你想要的驗證。其次,Rails有incrementing or decrementing values的內置方法。在你的情況,你可以改變你的控制器的方法是這樣的:

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

是的,他應該使用這些方法:+1 – Mischa 2012-01-11 04:20:48

相關問題