RubyonRails-模型中的多个引用
在一对多关系中,我有一个与另外三个模型具有多个关系的模型。我用这种方式手动创建了一个模型类RubyonRails-模型中的多个引用,ruby,ruby-on-rails-4,Ruby,Ruby On Rails 4,在一对多关系中,我有一个与另外三个模型具有多个关系的模型。我用这种方式手动创建了一个模型类 class Voter < ActiveRecord::Base belongs_to :city belongs_to :grp belongs_to :profession end 这合适吗 第二个问题是,是否可以使用多个引用运行“rails generate model”……来代替手动更改迁移文件,以便在迁移文件中自动添加多个引用?如果可以,您是如何做到的?您做得对。您完全可以通
class Voter < ActiveRecord::Base
belongs_to :city
belongs_to :grp
belongs_to :profession
end
这合适吗
第二个问题是,是否可以使用多个引用运行“rails generate model”……来代替手动更改迁移文件,以便在迁移文件中自动添加多个引用?如果可以,您是如何做到的?您做得对。您完全可以通过一个命令生成模型及其迁移:
rails generate model voter city:references grp:references profession:references firstname:string middlename:string lastname:string comments:text birthday:date
这将同时生成具有关系和正确迁移的模型
app/models/voter.rb:
class Voter < ActiveRecord::Base
belongs_to :city
belongs_to :grp
belongs_to :profession
end
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
类投票者
db/migrate/20151019104036\u create\u vorters.rb:
class Voter < ActiveRecord::Base
belongs_to :city
belongs_to :grp
belongs_to :profession
end
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
class
文件: