2013-08-03 47 views
4

我正在使用Rails 4與Devise,Cancan和Rollify。錯誤的參數數量(2代表1)Rails 4.也許strong_params問題

我有一個用戶改變角色的模式索引。然而,當我嘗試更新,我得到以下錯誤的角色:「錯誤的參數數目(2 1)」在我的用戶控制器代碼行16發生

錯誤:

13 def update 
14  authorize! :update, @user, message: 'Not authorized as an administrator.' 
15  @user = User.find(params[:id]) 
16  if @user.update_attributes(params[:user], as: :admin) 
17  redirect_to users_path, notice: "User updated." 
18  else 
19  redirect_to users_path, alert: "Unable to update user." 
20  end 
21 end 

形式正在發送params爲:

<div id="role-options-<%= user.id %>" class="reveal-modal medium" style="display: none;"> 
    <%= simple_form_for user, url: user_path(user), html: {method: :put, class: 'custom' } do |f| %> 
    <h3>Change Role</h3> 
    <%= f.input :role_ids, collection: Role.all, as: :radio_buttons, label_method: lambda {|t| t.name.titleize}, label: false, item_wrapper_class: 'inline', checked: user.role_ids.first %> 
     <%= f.submit "Change Role", class: "small button" %> 
     <a class="close-reveal-modal" href="#">Close</a> 
    <% end %> 
</div> 

這裏是我的榜樣:

class Role < ActiveRecord::Base 
    has_and_belongs_to_many :users, :join_table => :users_roles 
    belongs_to :resource, :polymorphic => true 

    scopify 
end 

我猜次它與從attr_accessible到Rails 4中強參數的變化有關,但我不確定。如果是,我在哪裏放置私人方法?

回答

2

此行包含錯誤,因爲update_attributes只接受一個參數,您試圖傳遞2個參數。我建議你將你的第二個參數與你的params[:user]哈希合併。

它應該是:

if @user.update_attributes(params[:user]) 

代替:

if @user.update_attributes(params[:user], as: :admin) 

希望它會help.Thanks

+0

謝謝你,所以當我將其更改爲 如果@ user.update_attibutes(PARAMS [:用戶]) 我現在得到了「::加載ActiveModel ForbiddenAttributesError」錯誤 –

+0

好吧,我去與一個私有方法計算出在我的用戶控制器中。 –

2

我遇到同樣的問題。我的解決方案是在用戶控制器中創建一個私有方法,並更改了更新參數。

private 
    def user_params 
    params.require(:user).permit! 
    end 

然後

if @user.update_attributes!(user_params) 

這工作得很好跟我來!

相關問題