属性を含むユーザーモデルを持つRailsアプリがありadmin
ます。を使用してロックダウンされattr_accessible
ます。私のモデルは次のようになります。
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.active_record.whitelist_attributes = true
しましたconfig/application.rb
。
current_user_role
メソッドが現在のユーザーの管理者ステータスに基づいて適切な値を返していることを確認しました。Railsは一括割り当てエラーをスローしていません。しかし、管理者としてログインしているときにユーザーの管理者ステータスを更新しようとすると、Railsは更新を実行し、admin
属性を黙って無視します。Railsコンソールでユーザーのレコードをプルアップすると、レコードが変更されていないことがわかります。
私は、RubyまたはRails固有の問題が発生していることに気づいていません。役割を動的にするための情報が見つかりません。私が見つけた最高のものはこれでした。