2012-03-15 59 views
8

我有一個包含admin屬性的用戶模型的Rails應用程序。它使用attr_accessible鎖定。我的模型是這樣的:Rails 3.2,批量分配,動態角色?

attr_accessible :name, :email, :other_email, :plant_id, :password, :password_confirmation 
attr_accessible :name, :email, :other_email, :plant_id, :password, :password_confirmation, :admin, :as => :admin 

這裏就是我的用戶控制我的更新方法是這樣的:

def update 
    @user = User.find(params[:id]) 
    if @user.update_attributes(params[:user], :as => current_user_role.to_sym) 
    flash[:notice] = "Profile updated" 
    redirect_to edit_user_url(@user) 
    else 
    render 'edit' 
    end 
end 

我在我的應用程序控制器,它傳回的角色作爲字符串一個輔助方法:

def current_user_role 
    @current_user_role ||= current_user.admin? ? "admin" : "default" 
end 
helper_method :current_user_role 

我也config/application.rb設置config.active_record.whitelist_attributes = true

我已驗證0123'方法是根據當前用戶的管理狀態返回適當的值。 Rails沒有拋出大規模分配錯誤。但是,當我以管理員身份登錄時嘗試更新用戶的管理員狀態時,Rails執行更新並默默忽略admin屬性。在Rails控制檯中拉出用戶的記錄顯示記錄沒有被修改。

我有一種感覺,我不知道有一個Ruby或Rails特定的問題。我找不到任何關於使角色變爲動態的信息。我能找到的最好的是this

+2

如果我正確理解你,你回答了你自己的問題。如果是這樣,你應該發佈你的答案作爲答案(而不是編輯你的問題)並接受它。 – 2012-06-21 03:27:05

回答

3

有一個錯誤的attr_accessor:在我的模型管理這是從先前的嘗試,在得到這個工作留給英寸我忽略了它。刪除它修好了。

所以,結果是,這是一個非常簡單的方法來獲取在Rails 3.2中工作的動態角色。