How can I, by default, associate a generic relationship with cancan with the internal node of the tree?

I use cancan to authorize my actions with the controller. One of the classes where cancan access is allowed is the tree implemented with act_as_ancestry . I am having problems using load_and_authorize_resourcewhen the user is not allowed access to the root level, but access is allowed, starting from the inside of the node.

Here are some definitions of a relavant class:

class User < ActiveRecord::Base
  belongs_to :organization, :inverse_of => :users
end

class Post < ActiveRecord::Base
  belongs_to :organization, :inverse_of => :posts
end

class Organization < ActiveRecord::Base
  has_ancestry :cache_depth => true
  has_many :users, :inverse_of => :organization
  has_many :posts, :inverse_of => :organization
end

Rules for managing messages: "You can manage messages in any organization below yours." My definition of cancan:

class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new 

    # subtree_ids is added by acts_as_ancestry
    can :manage, Post, {:organization_id => user.organization.subtree_ids}
  end
end

In the controller I have this (other actions omitted)

class PostsController < ApplicationController
  load_and_authorize_resource :post

  def index
  end

  def new
  end
end

, . , , node, , , can-can.

:

Access denied on new #<Post id: nil, organization_id: 1>

organization_id 1 () :

create_table "posts", :force => true do |t|
  t.integer  "organization_id", :default => 1
end

cancan Post @post. , , can Abilities.rb. , , , , .

, , ?

+5
2

cancan, @post , load_resource , . . : https://github.com/ryanb/cancan/wiki/Authorizing-controller-actions, "Override loading".

, - , , :

class PostsController < ApplicationController
  before_filter :initialize_post, :only => [:new, :create]

  def initialize_post
    @post = current_user.organization.posts.build(params[:post]||{:name=>'Smashing Kittens'})
  end

  load_and_authorize_resource :post
  def index
  end

  def new
  end

  def create
  end
end

, , : https://github.com/robmathews/cancan_test.

+3

, :

can :manage, Post do |post|
  post.organization.subtree_ids.include?(user.organization_id)
end
+1

All Articles