web-dev-qa-db-ja.com

移行中のt.belongs_to

シンプルなショッピングカートを作成するために、Ryan Batesの railscastsのソースコード #141を使用していました。移行の1つで、彼は

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

製品モデルは次のとおりです。

class Product < ActiveRecord::Base
 belongs_to :category
end

t.belongs_to :category行とは何ですか?それはt.integer category_idのエイリアスですか?

39
Tyler DeWitt

t.belongs_to :categoryは単なる 特別なヘルパーメソッド of Railsアソシエーションを渡すことです。

ソースコードbelongs_toは実際にはreferencesのエイリアスです

57
Justin Herrick
$ Rails g migration AddUserRefToProducts user:references 

これにより以下が生成されます。

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

12
shilovk

はい、エイリアスです。書くこともできますt.references category

11
Baldrick

add_belongs_to(table_name, *agrs)はあなたが探しているものです。 こちら について読むことができます

1
Bubunyo Nyavor

はい、t.belongs_to :category linet.integer category_idのエイリアスとして機能します。

MySQLでは、移行により次のようなテーブルが取得されます(2行目の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    |                |
+-------------+---------------+------+-----+---------+----------------+
0
mwfearnley