Aza*_*ram 9 ruby-on-rails database-migration rails-migrations
我有一个这样的Project迁移类:
class CreateProjects < ActiveRecord::Migration
def change
create_table :projects do |t|
t.string :title
t.text :description
t.boolean :public
t.references :user, index: true, foreign_key: true
t.timestamps null: false
end
end
end
Run Code Online (Sandbox Code Playgroud)
它user_id在项目表中创建一个列名,但我想命名列,owner_id以便我可以使用project.owner而不是project.user.
你可以用两种方式做到:
#app/models/project.rb
class Project < ActiveRecord::Base
belongs_to :owner, class_name: "User", foreign_key: :user_id
end
Run Code Online (Sandbox Code Playgroud)
要么
$ rails g migration ChangeForeignKeyForProjects
# db/migrate/change_foreign_key_for_projects.rb
class ChangeForeignKeyForProjects < ActiveRecord::Migration
def change
rename_column :projects, :user_id, :owner_id
end
end
Run Code Online (Sandbox Code Playgroud)
然后:
$ rake db:migrate
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8749 次 |
| 最近记录: |