Dan*_*nga 4 ruby ruby-on-rails-4
我有一个模型与一对多关系中的另外三个模型有多个关系.我以这种方式手动创建了一个Model类
class Voter < ActiveRecord::Base
belongs_to :city
belongs_to :grp
belongs_to :profession
end
Run Code Online (Sandbox Code Playgroud)
我有两个问题,
首先,如何创建具有多种关系的迁移?这是我的迁移文件
class CreateVoters < ActiveRecord::Migration
def change
create_table :voters do |t|
t.string :firstname
t.string :middlename
t.string :lastname
t.text :comments
t.date :birthday
t.references :city, index: true, foreign_key: true
t.timestamps null: false
end
end
end
Run Code Online (Sandbox Code Playgroud)
我想这样做
t.references :city, index: true, foreign_key: true
t.references :grp, index: true, foreign_key: true
t.references :profession, index: true, foreign_key: true
Run Code Online (Sandbox Code Playgroud)
这是对的吗?
第二个问题是,不是手动更改迁移文件,而是可以运行带有多个引用的"rails generate model"........以便在迁移文件中自动添加多个引用?如果可能,如何你做到了吗?
你没事.您可以在一个命令中完全生成具有迁移的模型:
rails generate model voter city:references grp:references profession:references firstname:string middlename:string lastname:string comments:text birthday:date
Run Code Online (Sandbox Code Playgroud)
这将同时生成您的关系和正确迁移的模型.
app/models/voter.rb:
class Voter < ActiveRecord::Base
belongs_to :city
belongs_to :grp
belongs_to :profession
end
Run Code Online (Sandbox Code Playgroud)
db/migrate/20151019104036_create_voters.rb:
class CreateVoters < ActiveRecord::Migration
def change
create_table :voters do |t|
t.references :city, index: true, foreign_key: true
t.references :grp, index: true, foreign_key: true
t.references :profession, index: true, foreign_key: true
t.string :firstname
t.string :middlename
t.string :lastname
t.text :comments
t.date :birthday
t.timestamps null: false
end
end
end
Run Code Online (Sandbox Code Playgroud)
文件:
| 归档时间: |
|
| 查看次数: |
2428 次 |
| 最近记录: |