首页 > 解决方案 > Rails 关联和迁移

问题描述

如果我想在我的“users”表中有一个“user_type”列引用另一个名为“user_type”的表,我如何在 rails 中编写正确的关联?例如,如果我的 user_type 是 1 并且 1 在我的 user_types 表中是管理员,并且当我在我的 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

但它不会工作

先感谢您

标签: ruby-on-railsmigration

解决方案


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

class UserType < ApplicationRecord
  has_many :users
end

class User < ApplicationRecord
  belongs_to :user_type
end

您应该阅读一次这个association_basics指南以了解关联在 Rails 中是如何工作的。


推荐阅读