I'm trying to use an after_create to set the default user role to subscriber. But it doesn't appear to make any changes. The roles of the new user is always [" " ].
User Model
class User < ActiveRecord::Base
acts_as_authentic
after_create :set_sub
after_create :set_universal
after_create :set_carrier
def set_sub
self.roles << "subscriber"
#self.roles_mask = 4
end
def set_universal
self.channels << Channel.find(1)
end
def set_carrier
@carrier = Carrier.with_name(self.carrier_name)
self.carrier<< @carrier
end
ROLES = %w[admin moderator subscriber]
#Each user can subscribe to many channels
has_and_belongs_to_many :channels
#Each user who is a moderator can moderate many channels
#has_many :channel_mods
has_and_belongs_to_many :modifies , :class_name => "Channel"
#Each user can receive many messages
has_and_belongs_to_many :messages
#Each user belongs to a carrier
belongs_to :carrier
#Filter users by role(s)
named_scope :with_role, lambda { |role| {:conditions => "roles_mask & #{2**ROLES.index(role.to_s)} > 0 "} }
def roles
ROLES.reject { |r| ((roles_mask || 0) & 2**ROLES.index(r)).zero? }
end
def roles=(roles)
self.开发者_运维知识库roles_mask = (roles & ROLES).map { |r| 2**ROLES.index(r) }.sum
end
def role_symbols
roles.map do |role|
role.underscore.to_sym # NOT role.name.underscore.to_sym (role is a string)
end
end
end
In the method set_stub you do self.roles << "subscriber"
, which doesn't do much. It modifies the array returned by roles, but nothing else.
You need to call self.role =
and do it before saving, so it gets saved.
def set_sub
self.roles = [ "subscriber" ]
end
The reason the other after_creates work, is because they work on a relation, which has the method <<
defined, and <<
on a relation saves instantly.
It's probably better to do this all using before_validation
and/or before_save
and be careful to set it, but not to save it. You could set self.channel_ids = [ 1 ]
, which will not trigger a save instantly, but will get saved when you call save
on the model.
精彩评论