rails generate model/resource/scaffold的区别


If you’re just learning Ruby on Rails, you may be confused as to when to generate individual models, resources or scaffolding, and what files are created by each command.

Say you want to generate a Test model with a name. You could either generate the model individually, generate resources, or generate scaffolding, as follows:

rails g model Test name:text
 
rails g resource Test name:text
 
rails g scaffold Test name:text

What’s the difference between each of the above?

EnteringrailsgmodelTestname:textin your command line will generate the following:

(1) A model filetest.rbin yourmodelsdirectory:

class Test < ActiveRecord::Base
end

(2) A migration filetimestamp_create_tests.rbin yourdb/migratedirectory:

class CreateTests < ActiveRecord::Migration
  def change
    create_table :tests do |t|
      t.text :name
 
      t.timestamps
    end
  end
end


EnteringrailsgresourceTestname:textin your command line will generate the following:

(1) A model filetest.rbin yourmodelsdirectory:

class Test < ActiveRecord::Base
end

(2) A migration filetimestamp_create_tests.rbin yourdb/migratedirectory:

class CreateTests < ActiveRecord::Migration
  def change
    create_table :tests do |t|
      t.text :name
 
      t.timestamps
    end
  end
end

(3) atests_controller.rbfile in yourcontrollersdirectory. This controller will be an empty shell:

class TestsController < ApplicationController
end

(4)resources:testsroutes in yourroutes.rbfile.



EnteringrailsgscaffoldTestname:textin your command line will generate the following:

(1) A model filetest.rbin yourmodelsdirectory:

class Test < ActiveRecord::Base
end

(2) A migration filetimestamp_create_tests.rbin yourdb/migratedirectory:

class CreateTests < ActiveRecord::Migration
  def change
    create_table :tests do |t|
      t.text :name
 
      t.timestamps
    end
  end
end

(3) Atests_controller.rbfile in yourcontrollersdirectory. When a scaffold is generated, seven public methods and two private methods will be added to your controller:

(4)resources:testsroutes in yourroutes.rbfile.

(5) Seven corresponding view files in yourviewsdirectory: (a)_form.html.erb, (b)edit.html.erb, (c)index.html.erb, (d)index.json.jbuilder, (e)new.html.erb, (f)show.html.erband (g)show.json.jbuilder. Each view will contain html and embedded ruby.

优质内容筛选与推荐>>
1、Spring Boot Unregistering JMX-exposed beans on shutdown
2、跨平台 webapp 开发技术之 Hybrid App
3、[转]fiddler 抓包 HTTPS 请求
4、php的内核组成模块
5、Web学习笔记


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号





    联系我们

    欢迎来到TinyMind。

    关于TinyMind的内容或商务合作、网站建议,举报不良信息等均可联系我们。

    TinyMind客服邮箱:support@tinymind.net.cn