模型中的before_create方法在创建用户时不起作用 - Rails4

时间:2016-11-16 15:22:24

标签: ruby-on-rails

  • 我不确定为什么我的代码无效 - 您的帮助将不胜感激
  • 我想要做的是:创建用户时,用户被分配到角色"客户端"和小组"客户组"

问题:我不确定为什么我的before_create行动不起作用。有人可以就此提出建议吗?

我收到错误消息:

NoMethodError - undefined method `name' for nil:NilClass:

我发现这很奇怪,因为当我在我的终端中查看我的类别时,一切似乎都很好 enter image description here

  

user.rb

user belongs_to :category_role
user belongs_to :category_managementgroup

before_create :assign_user_to_role_and_group

def assign_user_to_role_and_group
    self.category_role.name == "Client"
    self.category_managementgroup.name == "Client Group"
  end
  

category_role.rb

has_many :users
  

category_managementgroup.rb

has_many :users
  

seed.rb

CategoryRole.delete_all
cr01 = CategoryRole.create!(name:'Admin')
cr02 = CategoryRole.create!(name:'Primary Admin')
cr03 = CategoryRole.create!(name:'Client')

CategoryManagementgroup.delete_all
cmr01 = CategoryManagementgroup.create!(name:'Administration Group')
cmr02 = CategoryManagementgroup.create!(name:'Client Group')
cmr03 = CategoryManagementgroup.create!(name:'Management Group')
  

模式

create_table "users", force: :cascade do |t|
    t.string   "email",                         default: "", null: false
    t.integer  "category_role_id"
    t.integer  "category_managementgroup_id"
  end

create_table "category_roles", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

create_table "category_managementgroups", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

1 个答案:

答案 0 :(得分:1)

你可能意味着这样的事情:

PRODUCT_STATUS

即实际上角色和组分配给各个类的实际对象