ruby-on-rails - 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
但它不会工作
先感谢您
解决方案
这就是您应该如何定义模型关联。
class UserType < ApplicationRecord
has_many :users
end
class User < ApplicationRecord
belongs_to :user_type
end
您应该阅读一次这个association_basics指南以了解关联在 Rails 中是如何工作的。
推荐阅读
- python-3.x - 如何在 matplotlib 3-D 散点图上表示密度信息
- qt - 如何将悬停或鼠标区域更新事件传播到 QML 中的较低元素?
- date - 是否可以批量专门比较两个日期?
- python - 删除熊猫中的无效行
- macos - 从 tarball 中删除目录的跨平台方法
- linux - 内核内存增长在 docker 容器中的 ubuntu 中创建文件
- packer - 使用打包器创建图像时,我们如何从 Gitlab 获取代码?
- reactjs - 由于选择器未定义,Jest 单元测试失败
- pycharm - Pycharm/Pytorch - '张量' 不可调用
- laravel - Laravel 5.7 中的身份验证会话