当我的作业与has_many上的用户模型相关时,如何自动为用户分配角色? Rails 3

时间:2011-02-24 23:15:41

标签: ruby-on-rails ruby-on-rails-3 associations

我想要做的是创建用户时,它会自动为他们提供角色。

问题在于角色通过分配表和has_many通过关联与用户相关。

代码如下:

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        :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

1 个答案:

答案 0 :(得分:4)

首先,不要使用硬编码的ID来找到你可能会改变的角色。

其次,使用关联构建器,或者自己访问角色关联。

第三,在命名方法时遵循“不要让我思考”(DMMT)的规则。

记住这三件事:

def assign_default_role
  self.roles << Role.find_by_name("User")
end