Check if current_user is the owner of a resource and allow edit/delete actions

后端 未结 9 746
鱼传尺愫
鱼传尺愫 2021-02-02 00:02

Example:

User A (id=10) has created a photo resource

photo: (id: 1 user_id = 10, url: \"http://...\")
         


        
9条回答
  •  [愿得一人]
    2021-02-02 00:57

    Write another before_filter in application_controller:

    before_filter :has_permission?
    
    has_permission?
    controllers=["articles", "photos", "..."]
    actions=["edit", "destroy", "..."]
    id = params[:id] if (controllers.include?(params[:controller] && actions.include?(params[:action]) end
    if id && (current_user.id==(params[:controller][0...1].capitalize!+params[:controller].singularize[1...-1] + ".find(#{id}).user_id").send)
    return true
    else
    redirect_to root_url, :notice=>"no permission for this action"
    end
    
    helper_method :has_permission?
    

    And you can use it in views, not to show users link they can't follow.

    Some kind of this, of course you need to modify it to suit your needs.

提交回复
热议问题