Ruby-on-rails t.belongs_to 在迁移中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9471091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
t.belongs_to in migration
提问by Tyler DeWitt
I was using Ryan Bates's source code for railscasts#141 in order to create a simple shopping cart. In one of the migrations, he lists
我使用 Ryan Bates 的railscasts#141源代码来创建一个简单的购物车。在其中一次迁移中,他列出了
class CreateProducts < ActiveRecord::Migration
def self.up
create_table :products do |t|
t.belongs_to :category
t.string :name
t.decimal :price
t.text :description
t.timestamps
end
end
def self.down
drop_table :products
end
end
Here is the Product model:
这是产品型号:
class Product < ActiveRecord::Base
belongs_to :category
end
What is the t.belongs_to :categoryline? Is that an alias for t.integer category_id?
什么是t.belongs_to :category线?那是 的别名t.integer category_id吗?
回答by Justin Herrick
The t.belongs_to :categoryis just a special helper methodof rails passing in the association.
该t.belongs_to :category仅仅是一个特殊的helper方法传入协会轨道。
If you look in the source codebelongs_tois actually an alias of references
如果你看源码belongs_to其实是一个别名references
回答by shilovk
$ rails g migration AddUserRefToProducts user:references
this generates:
这会产生:
class AddUserRefToProducts < ActiveRecord::Migration
def change
add_reference :products, :user, index: true
end
end
http://guides.rubyonrails.org/active_record_migrations.html#creating-a-standalone-migration
http://guides.rubyonrails.org/active_record_migrations.html#creating-a-standalone-migration
回答by Baldrick
Yes, it's an alias; It can also be written t.references category.
是的,它是一个别名;也可以写t.references category。
回答by Bubunyo Nyavor
回答by mwfearnley
Yes, t.belongs_to :categoryacts as an alias for t.integer category_id, in that it causes an appropriately typed category_idfield to be created.
是的,t.belongs_to :category充当 的别名t.integer category_id,因为它会导致category_id创建适当类型的字段。
In MySQL, the migration gets me a table like this (note the category_idfield on the second row):
在 MySQL 中,迁移给我一个这样的表(注意category_id第二行的字段):
mysql> describe products;
+-------------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| category_id | int(11) | YES | | NULL | |
| name | varchar(255) | YES | | NULL | |
| price | decimal(10,0) | YES | | NULL | |
| description | text | YES | | NULL | |
| created_at | datetime | YES | | NULL | |
| updated_at | datetime | YES | | NULL | |
+-------------+---------------+------+-----+---------+----------------+

