Ruby on rails Rails关联和迁移

Ruby on rails Rails关联和迁移,ruby-on-rails,migration,Ruby On Rails,Migration,如果我想在“users”表中有一个“user\u type”列引用另一个名为“user\u type”的表,那么如何在rails中编写正确的关联?例如,如果我的user_type是1,并且在我的user_type表中1是admin,那么当我在rails控制台中编写这个时 user = User.first user.user_type #I want this to return admin 我试过了 class AddTypeToUsers < ActiveRecord::Migrat

如果我想在“users”表中有一个“user\u type”列引用另一个名为“user\u type”的表,那么如何在rails中编写正确的关联?例如,如果我的user_type是1,并且在我的user_type表中1是admin,那么当我在rails控制台中编写这个时

user = User.first
user.user_type #I want this to return admin
我试过了

class AddTypeToUsers < ActiveRecord::Migration[5.2]
  def change
    add_reference :users, :user_type, foreign_key: true
  end
end
类AddTypeToUsers 但这行不通


提前感谢您

这是您应该如何定义模型关联的

class UserType < ApplicationRecord
  has_many :users
end

class User < ApplicationRecord
  belongs_to :user_type
end
class UserType

您应该阅读本指南一次,以了解关联在Rails中的工作方式。

谢谢您的帮助,但是如果我键入
user.user\u type=1
它将返回
UserType expected,got 1这是integer的一个实例
user.user\u type\u id=1
您需要做什么,else
user.user\u type=
object
add\u reference
方法在
users
表中添加了一个
user\u type\u id
列,请检查schema.rb文件。@johnuno我想说的一件事是,它更有意义
UserRole
,而不是
UserType
IMO:)