2012-01-20 5 views
3

のは、私のようなモデル「チャネル」があるとしましょう(コースは論理属性です): cancanを使用している間にどのようにスコープ付き一括割り当てを設定しますか?

class Ability 
    include CanCan::Ability 

    def initialize(user) 
    if user 
     if user.administrator 
     can :manage, Channel 
     else 
     can [:read, :create], Channel 
     can [:update, :destroy], Channel, :course => false 
     end 
    end 
    end 
end 

はここに私の現在のコントローラです:

class Channel < ActiveRecord::Base 
    attr_accessible :title 
    attr_accessible :course, :title, :as => :administrator 
end 

私は、次の機能のセットアップとカンカンを使用していますセットアップ:私は更新する機能を持っていることから、管理者以外のユーザーを防ぐために、私のコントローラにカンカンのload_and_authorize_resource方法を必要とする

class ChannelsController < ApplicationController 
    load_and_authorize_resource 

    ### 

    def new 
    end 

    def create 
    if @channel.save 
     redirect_to @channel, :notice => "Successfully created channel." 
    else 
     render :action => 'new' 
    end 
    end 

    def edit 
    end 

    def update 
    if @channel.update_attributes(params[:channel]) 
     redirect_to @channel, :notice => "Successfully updated channel." 
    else 
     render :action => 'edit' 
    end 
    end 

    ### 

end 

コースが真である既存のチャンネルがありますが、current_user.administratorに基づいてif/elseでリソースの読み込みを中断して、:as => :administratorのスコープを設定して、管理者がコース属性にアクセスできるようにする必要もあります。

これを行うには賢明な方法がありますか?

def update 
    @channel.assign_attributes(params[:channel], 
      :as => (current_user.administrator ? :administrator : :default) 
    if @channel.save 
    redirect_to @channel, :notice => "Successfully updated channel." 
    else 
    render :action => 'edit' 
    end 
end 

createアクションのために、私は最も簡単な解決策は、手動で割り当てと承認を行うことだと思う:大量の割り当てがload_and_authorize_resourceupdate_attributesとしないことによって行われるため、update方法を修正

+0

こんにちは、何とかこれをやりましたか?私はまったく同じ状況にいる! – kikito

+0

チャネルとコースを2つの別々のモデルに分割してしまったのは、それぞれを扱う方法が十分に分かれていたからです。おそらくそれほど助けにならないでしょう、申し訳ありません。 – Preacher

答えて

0

は非常に簡単です:あなたはこのをたくさんやって終わる

load_and_authorize_resource :except => :create 

## ---- 

def create 
    @channel = Channel.new 
    @channel.assign_attributes(params[:channel], 
      :as => (current_user.administrator ? :administrator : :default) 
    if @channel.save 
    redirect_to @channel, :notice => "Successfully created channel." 
    else 
    render :action => 'new' 
    end 
end 

場合、代わりにload_and_authorize_resourceの簡単なカスタムフィルタを使用するように価値があるかもしれません。

関連する問題