[英]Why doesn't 'rails g scaffold' generate a db migration when invoked with a '--parent' argument?
我正在尝试在Rails应用中将User
子类化(Rails 4.2.0,Devise 3.5.2)
如果我使用--parent user
参数调用生成器,则不会生成数据库迁移:
$ rails g scaffold participant token:string --parent user
invoke active_record
create app/models/participant.rb
invoke test_unit
create test/models/participant_test.rb
create test/fixtures/participants.yml
invoke resource_route
route resources :participants
invoke scaffold_controller
create app/controllers/participants_controller.rb
invoke haml
create app/views/participants
create app/views/participants/index.html.haml
create app/views/participants/edit.html.haml
create app/views/participants/show.html.haml
create app/views/participants/new.html.haml
create app/views/participants/_form.html.haml
invoke test_unit
create test/controllers/participants_controller_test.rb
invoke helper
create app/helpers/participants_helper.rb
invoke test_unit
invoke jbuilder
create app/views/participants/index.json.jbuilder
create app/views/participants/show.json.jbuilder
invoke assets
invoke coffee
create app/assets/javascripts/participants.coffee
invoke scss
create app/assets/stylesheets/participants.scss
invoke scss
identical app/assets/stylesheets/scaffolds.scss
在没有--parent user
情况下调用生成器会导致生成数据库迁移(请参见第三行):
$ rails g scaffold participant token:string
invoke active_record
create db/migrate/20160109231939_create_participants.rb
create app/models/participant.rb
invoke test_unit
create test/models/participant_test.rb
create test/fixtures/participants.yml
invoke resource_route
route resources :participants
invoke scaffold_controller
create app/controllers/participants_controller.rb
invoke haml
create app/views/participants
create app/views/participants/index.html.haml
create app/views/participants/edit.html.haml
create app/views/participants/show.html.haml
create app/views/participants/new.html.haml
create app/views/participants/_form.html.haml
invoke test_unit
create test/controllers/participants_controller_test.rb
invoke helper
create app/helpers/participants_helper.rb
invoke test_unit
invoke jbuilder
create app/views/participants/index.json.jbuilder
create app/views/participants/show.json.jbuilder
invoke assets
invoke coffee
create app/assets/javascripts/participants.coffee
invoke scss
create app/assets/stylesheets/participants.scss
invoke scss
identical app/assets/stylesheets/scaffolds.scss
为什么指定父类会禁止创建数据库迁移? 我无法想到某种无法以某种方式保留到数据库的模型的合法使用。
将字符串type
字段添加到参与者模型以启用单表继承无效。
--parent
选项与单表继承结合使用。
我无法想到某种无法以某种方式持久化到数据库的模型的合法使用
但这正是STI所做的。 它使您可以在一个表中存储多个实体(模型)。
考虑将模型User
存储在表users中 。 该表具有一列is_admin 。
您可以拥有一个单独的模型Admin
,该模型将共享users表,但仅适用于is_admin标志设置为true
。
最初,您生成User
模型
rails g model User name:string is_admin:boolean
然后,创建将继承自User
且不需要它自己的表的Admin
模型
rails g model Admin --parent user
--parent
选项假定您已经为单一表继承做好了准备,即父类的表具有type
列(或您为此使用的任何列)。
由于模型将存储在父表中,因此无需为子类创建新表,因此无需迁移。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.