简体   繁体   中英

Allowing cancan Ability.rb manage access only specific fields of a model

I'm trying to add a button to mark a reply as read in Rails. I currently have something like this.

# /app/models/ability.rb
...
can :manage, Reply, :user_id => user.id
...

I have also load_and_authorize_resource in my RepliesController

# /app/controllers/replies_controller.rb
class RepliesController < ApplicationController
  load_and_authorize_resource

  def update 
    @reply = Reply.find(params[:id])
    @reply.isRead = true
    if @reply.save
      flash[:notice] = "Marked as ready."
      flash[:alert] = params[:id]
      redirect_to root_path
    else
      render :action => 'new'
    end
  end

I have a button where users can mark a Reply as read.

  = button_to "Mark as read", idea_reply_path(reply.idea,reply), :method => "put"

Problem is that since I'm trying to update an object from other user.id owner as defined in ability.rb (top) I don't have privileges to edit it.

If I add something like this It will work but I'm also giving rights to manage the whole reply object to the other person.

can :manage, Reply, :to_user_id => user.id

I'm needing a way to only allow the user to manage the attribute isRead? of an object where he's user.id matches the to_user_id .

You can define a new action for in the controller like mark_as_read

 def mark_as_read
  #action to mark as read  
 end

and in the abilities define

can :manage, :Reply, :user_id => user.id
can :mark_as_read, :to_user_id => user.id

The ordering is very important. Now the logged in User can manage Replies and the user who is the user will have only ability to mark_as_read.

I think you can have both

can :manage, Reply, :user_id => user.id
can :update, Reply, :to_user_id => user.id

If update action is only for mark Reply as read then that's what you want

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM