加入协会已有的模型 [英] add associations to exisiting models

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

问题描述

我不知道我该怎么加协会,我的模型。假如,我产生两种型号

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表应用此修改?我打算使用该表在我的code。

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 列它对应的表。由于汽车belongs_to的用户,汽车表应该有一个 USER_ID 列。这可以通过2种方式。

belongs_to association expect an association_id column in it's 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

你创建了副总裁Richard Brown的回答模型后,

或只是添加USER_ID。要小心,如果你使用整数而不是引用,你必须自己创建索引。

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

更新:

约瑟夫在评论中提到,需要手动添加已经在Rails中的当前版本中得到解决的索引。我认为这是对Rails 4.介绍您可以在<读多了吧href=\"http://edgeguides.rubyonrails.org/active_record_migrations.html#creating-a-standalone-migration\">official 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

将创建一个迁移类似于一个行

will create a migration with a line similar to

add_reference :cars, :user, index: true

这会 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天全站免登陆