2012-02-27 15 views
31

Użyłem Ryana Batesa source code for railscasts # 141 w celu utworzenia prostego koszyka na zakupy. W jednej z wędrówek, wymienia ont.belongs_to w migracji

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 

Oto model produktu:

class Product < ActiveRecord::Base 
belongs_to :category 
end 

Co jest linia t.belongs_to :category? Czy to jest alias dla t.integer category_id?

Odpowiedz

10

Tak, to alias; Może być również napisane t.references category.

+0

Prawie. 't.references' teraz dodaje również ograniczenie klucza obcego. https://apidock.com/rails/ActiveRecord/ConnectionAdapters/Table/references –

1

add_belongs_to(table_name, *agrs) jest to, czego szukasz. Możesz przeczytać o here

0

Tak, t.belongs_to :category line działa jako alias dla t.integer category_id.

W MySQL, migracja staje mi stolik tak (uwaga na pole category_id w drugim rzędzie):

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 |    | 
+-------------+---------------+------+-----+---------+----------------+ 
Powiązane problemy