Question

I want to get a list of say moderators from User model, it works in this case

u = User.new(:name => "n", :surname => "s", :email => "a@m.c", :password => "x")
u.add_role(:moderator)
u.save!

but if i assign a resource to User model like this, it's not listing users with role moderator

u = User.new(:name => "m", :surname => "b", :email => "a@m.c", :password => "x")
u.add_role(:moderator, Post.first)
u.save!

UPDATE

post.rb

class Post < ActiveRecord::Base
  attr_accessible :user_id, :content
  belongs_to :user
end

user.rb

class User < ActiveRecord::Base
  rolify
end
Was it helpful?

Solution

You should add resourcify to your Post model and other all models you want to apply roles on, as described in readme.

So, your Post model should look like:

Post.rb

class Post < ActiveRecord::Base
  resourcify
  attr_accessible :user_id, :content
  belongs_to :user
end

* EDIT *

You can get all users with role :admin using User.with_all_roles({:name => :admin})

I've created a vanilla project uses rolify with same User and Post model. Change Post model and add resourcify, change User model and add has_many :posts

user = User.create(...)
user.add_role :admin
post = user.posts.create(...)
user2 = User.create(...)
user2.add_role(:moderator, post)

Seems working with these:

  • User.with_all_roles({:name => :admin})
  • User.with_all_roles({:name => :moderator, :resource => Post })
  • User.with_all_roles({:name => :moderator, :resource => Post.first })
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top