将关联添加到现有模型 [英] add associations to exisiting models

查看:41
本文介绍了将关联添加到现有模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何为我的模型添加关联.假设,我生成了两个模型

I'm wondering how I can add associations to my models. Suppose, I generate two models

rails generate model User
rails generate model Car

现在我想添加一个关联,以便模型获取表单

Now I want to add an associations so that the models acquire the form

class User < ActiveRecord::Base
  has_many :cars
end
class Car < ActiveRecord::Base
  belongs_to :user
end

问题是:如何通过迁移应用此修改以获取数据库中的cars_users表?我打算在我的代码中使用该表.

The question is: how to apply this modification by migrations in order to obtain cars_users table in the database? I'm planning to use that table in my code.

推荐答案

belongs_to 关联期望在其对应表中有 association_id 列.由于汽车属于用户,汽车表应该有一个 user_id 列.这可以通过两种方式完成.

belongs_to association expect an association_id column in its corresponding table. Since cars belongs_to user, the cars table should have a user_id column. This can be accomplished 2 ways.

首先,您可以在创建模型时生成列

first, you can generate the column when you create the model

rails g model car user_id:references

或者在创建模型后添加 user_id 就像 Richard Brown 的回答一样.请注意,如果您使用 integer 而不是 references,则必须自己创建索引.

or just add the user_id after you create the model like Richard Brown's answer. Be careful that if you use integer instead of references, you'd have to create the index yourself.

rails g migration add_user_id_to_cars user_id:integer

然后在生成的迁移中,添加

then in the generated migration, add

add_index :cars, :user_id

更新:

正如 Joseph 在评论中提到的,手动添加索引的需要已经在当前版本的 Rails 中解决了.我认为它是在 Rails 4 中引入的.您可以在 中阅读更多内容官方 Rails 迁移指南.它的要点是运行以下生成器

As Joseph has mentioned in the comments, the need to add the index manually has already been addressed in the current version of Rails. I think it was introduced in Rails 4. You can read more of it in the official Rails guide for migrations. The gist of it is running the following generator

bin/rails g migration add_user_to_cars user:references

将创建一个类似于

add_reference :cars, :user, index: true

这会在cars 表中添加一个user_id 列,并且还会将该列标记为要编入索引.

This will add a user_id column to the cars table and it will also mark that column to be indexed.

这篇关于将关联添加到现有模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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