How do I automatically assign a role to a user when my assignment is related to user model on a has_many through ? Rails 3
What I would like to do is when a user is created, it automatically gives them a role.
The thing is that the role is related to the user via an assignment table and a has_many through association.
The code is as follows:
User model
# == Schema Information
# Schema version: 20110214082231
#
# Table name: users
#
# id :integer not null, primary key
# email :string(255)
# encrypted_password :string(128)
# password_salt :string(255)
# reset_password_token :string(255)
# remember_token :string(255)
# remember_created_at :datetime
# sign_in_count :integer
# current_sign_in_at :datetime
# last_sign_in_at :datetime
# current_sign_in_ip :string(255)
# last_sign_in_ip :string(255)
# username :string(255)
# f_name :string(255)
# l_name :string(255)
# created_at :datetime
# updated_at :datetime
# invitation_token :string(60)
# invitation_sent_at :datetime
# plan_id :integer
# current_state 开发者_Python百科 :string(255)
# confirmation_token :string(255)
# confirmed_at :datetime
# confirmation_sent_at :datetime
#
class User < ActiveRecord::Base
before_create :assign
has_many :assignments
has_many :roles, :through => :assignments
def role_symbols
roles.map do |role|
role.name.underscore.to_sym
end
end
def assign
@assignment.build_role(:user_id => self.id, :role_id => '3')
end
end
Assignments model
# Table name: assignments
#
# id :integer not null, primary key
# user_id :integer
# role_id :integer
# created_at :datetime
# updated_at :datetime
#
class Assignment < ActiveRecord::Base
belongs_to :role
belongs_to :user
end
Role model
# == Schema Information
# Schema version: 20101117094659
#
# Table name: roles
#
# id :integer not null, primary key
# name :string(255)
# created_at :datetime
# updated_at :datetime
#
class Role < ActiveRecord::Base
has_many :assignments
has_many :users, :through => :assignments
end
Firstly, don't use hard-coded ids to find your roles as they may change.
Secondly, use association builders, or just access the roles association yourself.
Thirdly, follow the rule of "Don't Make Me Think" (DMMT) when naming your methods.
With these three things in mind:
def assign_default_role
self.roles << Role.find_by_name("User")
end
精彩评论