What I’m trying to do is set role to “user” for all users, but I haven’t used the console or Ruby much, which should be clear from the way I’m trying to use them below.
I had hoped something like this would work:
u=User.all
u.role.name="user"
But, clearly, that’s not working and I’m not sure how to proceed.
I’m using CanCan with an ability model and setting the role name by a “name” column in roles. users have many roles through assignments
user.rb
has_many :assignments
has_many :roles, :through => :assignments
Here’s how everything is set up:
assignment.rb
class Assignment < ActiveRecord::Base
belongs_to :user
belongs_to :role
end
ability.rb
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # in case of guest
if user.has_role? :admin
can :manage, :all
#else
# can :read, :all
end
end
end
role.rb
class Role < ActiveRecord::Base
attr_accessible :name
has_and_belongs_to_many :users, :join_table => :users_roles
belongs_to :resource, :polymorphic => true
end
roles schema
# == Schema Information
#
# Table name: roles
#
# id :integer not null, primary key
# name :string(255)
# resource_id :integer
# resource_type :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
Can you let me know how I would set the role name for all users using console?
Use
update_all:However,
update_allwill not trigger ActiveRecord callbacks, so if you need those you instead need to iterate over all users:User.find_eachloads users in batches to minimize memory usage if you have more than 1000 users.