![](/img/trans.png)
[英]Rails belongs_to association returning “Undefined Method” error
[英]Rails belongs to association method undefined
嗨,我与Rails协会有问题。 我有表用户和表角色。 这是我的迁移:
class CreateUsers < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
t.string :email
t.string :password_digest
t.belongs_to :role, index: true, foreign_key: true
t.timestamps
end
end
end
class CreateRoles < ActiveRecord::Migration[5.2]
def change
create_table :roles do |t|
t.string :name
t.string :code
t.timestamps
end
end
end
我在创建具有以前创建的角色的用户时遇到问题
Role.create(name: 'Super Admin', code: 'super_admin')
User.create(email: 'a@b.com', password: 'abcdefg', role_id: 1)
当我尝试执行User.first.role时,我发现方法角色未定义。 据我所知,当我这样做时,我应该获得一个活跃的角色记录。
我做错了。 请帮忙
您需要将关系添加到模型中。 在user.rb中:
class User < ApplicationRecord
belongs_to :role
# other code
end
它将生成您要查找的ActiveRecord方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.