活动记录迁移 rails 4 中的 has_many、belongs_to 关系 [英] has_many, belongs_to relation in active record migration rails 4

查看:41
本文介绍了活动记录迁移 rails 4 中的 has_many、belongs_to 关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 User 模型和一个 Task 模型.我在创建它们时没有提到它们之间的任何关系.

I have a User model and a Task model. I have not mentioned any relation between them while creating them.

我需要建立那个 User has_many Tasks 和一个 Task belongs_toUser 通过迁移

I need to establish that User has_many Tasks and a Task belongs_to User through a migration

用于建立这种关系的迁移生成命令是什么?

What would be the migration generation command for establishing that relationship?

推荐答案

您可以致电:

rails g model task user:references

将在 tasks 表中生成一个 user_id 列,并将修改 task.rb 模型以添加一个 belongs_to :用户 关系.请注意,您必须手动将 has_many :taskshas_one :task 关系放入 user.rb 模型.

which will generates an user_id column in the tasks table and will modify the task.rb model to add a belongs_to :user relatonship. Please note, you must to put manually the has_many :tasks or has_one :task relationship to the user.rb model.

如果您已经生成了模型,则可以使用以下内容创建迁移:

If you already have the model generated, you could create a migration with the following:

rails g migration AddUserToTask user:belongs_to

将生成:

class AddUserToTask < ActiveRecord::Migration
  def change
    add_reference :tasks, :user, index: true
  end
end

这种方法的唯一区别是,task.rb 模型中的 belongs_to :user 关系不会自动创建,因此您必须为您的自己的.

the only difference with this approach is, the belongs_to :user relationship in the task.rb model won't be created automatically, so you must create it for your own.

这篇关于活动记录迁移 rails 4 中的 has_many、belongs_to 关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆