Ruby-on-rails – use Cancan to authorize resources based on multi-to-many associations

I have two models, events and users share many-to-many associations. Users can be administrators, managers or producers.
Only the producer belonging to an event can read Take the event. I tried to apply this restriction on the ability model, but it failed. Every producer can read all events. What am I doing wrong?

class Event  has_and_belongs_to_many :producers, :class_name => "User", :join_table => "events_producers"
end


class CreateEventUserJoinTable def self.up
create_table :events_producers, :id => false do |t|
t.integer :event_id
t.integer :user_id
end
end

def self.down
drop_table :events_producers
end
end

class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new() # Guest user
if user.role? :manager
can :manage, :all
elsif user.role? :admin
can :read, Event
can :update, Event
can :create, Event
elsif user.role? :producer
can :read, Event do |event|
event.try(:producers).include?(user)
end
end
end
end

The problem is that when class-based calls (for example, class-based calls), the conditions in the capability block are not used. Index actions. For instructions, please See https://github.com/ryanb/cancan/wiki/Defining-Abilities-with-Blocks.

For index operations, you must define restrictions outside the block.

< /div>

I have two models, events and users share many-to-many associations. Users can be administrators, managers or producers.
Only the producer belonging to an event can read The event. I tried to apply this restriction on the capability model, but it failed. Every producer can read all events. What am I doing wrong?

class Event  has_and_belongs_to_many :producers, :class_name => "User", :join_table => "events_producers"
end


class CreateEventUserJoinTable def self.up
create_table :events_producers, :id => false do |t|
t.integer :event_id
t.integer :user_id
end
end

def self.down
drop_table :events_producers
end
end

class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new() # Guest user
if user.role? :manager
can :manage, :all
elsif user.role? :admin
can :read, Event
can :update, Event
can :create, Event
elsif user.role? :producer
can :read, Event do |event|
event.try(:producers).include?(user)
end
end
end
end

The problem is that when class-based When calling (for example, class-based calls), the conditions in the ability block are not used. Index actions. For instructions, see https://github.com/ryanb/cancan/wiki/Defining-Abilities-with-Blocks. < p>

For index operations, you must define restrictions outside the block.

WordPress database error: [Table 'yf99682.wp_s6mz6tyggq_comments' doesn't exist]
SELECT SQL_CALC_FOUND_ROWS wp_s6mz6tyggq_comments.comment_ID FROM wp_s6mz6tyggq_comments WHERE ( comment_approved = '1' ) AND comment_post_ID = 3316 ORDER BY wp_s6mz6tyggq_comments.comment_date_gmt ASC, wp_s6mz6tyggq_comments.comment_ID ASC

Leave a Comment

Your email address will not be published.