CanCan: limiting a user's ability to set certain model attributes based on their role

后端 未结 4 1634
耶瑟儿~
耶瑟儿~ 2020-12-29 06:10

I have a Post model with a :published attribute (boolean) and a User model with a role attribute (st

4条回答
  •  天命终不由人
    2020-12-29 06:41

    Check out this post: How do I use CanCan with rails admin to check for ownership

    It shows how to make a field not visible based off a users role.

    UPDATE I was able to set options in rails admin with this code:

    config.model User do
      edit do
        configure :organization do
          visible do
            bindings[:view]._current_user.max_role_name != 'admin' ? false : true
          end
        end
    
        configure :organization_id, :hidden do
          visible do
            true if bindings[:view]._current_user.max_role_name != 'admin'
          end
          default_value do
            bindings[:view]._current_user.organization_id if bindings[:view]._current_user.max_role_name != 'admin'
          end
        end
    
        include_all_fields
      end
    end
    

    This configuration will hide the organization field if the logged in user is not an admin. It will then show an organization_id field ( set to type='hidden' ) and set the default value.

    Hope this helps someone.

提交回复
热议问题