t.belongs_to在迁移中

Tyl*_*itt 40 database migration ruby-on-rails

我正在使用Ryan Bates的railscast#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
Run Code Online (Sandbox Code Playgroud)

这是产品型号:

class Product < ActiveRecord::Base
 belongs_to :category
end
Run Code Online (Sandbox Code Playgroud)

什么是t.belongs_to :category线?这是别名t.integer category_id吗?

Jus*_*ick 59

这t.belongs_to :category只是关联中rails传递的一种特殊辅助方法.

如果查看源代码 belongs_to实际上是别名references


shi*_*ovk 13

$ rails g migration AddUserRefToProducts user:references 
Run Code Online (Sandbox Code Playgroud)

这会产生:

class AddUserRefToProducts < ActiveRecord::Migration
  def change
    add_reference :products, :user, index: true
  end
end
Run Code Online (Sandbox Code Playgroud)

http://guides.rubyonrails.org/active_record_migrations.html#creating-a-standalone-migration


Bal*_*ick 12

是的,这是一个别名; 它也可以写t.references category.

  • 几乎。`t.references` 现在还添加了外键约束。https://apidock.com/rails/ActiveRecord/ConnectionAdapters/Table/references (2认同)

Jac*_*ack 7

第一:迁移

rails generate migration add_user_to_products user:belongs_to

(在这种情况下)相当于

rails generate migration add_user_to_products user:references

并且两者都创造了

class AddUserToProducts < ActiveRecord::Migration
  def change
    add_reference :products, :user, index: true
  end
end
Run Code Online (Sandbox Code Playgroud)

您可以将其“解读”add_reference :products, :user, index: true为“产品属于用户”

在架构中,迁移将在items表中创建一个名为 的字段"user_id"。这就是该类被称为 的原因AddUserToProducts。迁移将该user_id字段添加到产品中。

第二:型号

然后他应该更新产品模型,因为迁移只会改变架构。他也必须用类似的东西来更新用户模型

class User < ActiveRecord::Base
 has_many :products
end
Run Code Online (Sandbox Code Playgroud)

一般来说

rails g migration add_[model linking to]_to_[table containing link] [model linking to]:belongs_to

注:g是缩写generate

class User < ActiveRecord::Base
 has_many :[table containing link]
end
Run Code Online (Sandbox Code Playgroud)