rails generate model/resource/scaffold的区别

本文详细解释了Ruby on Rails中生成模型、资源和脚手架的区别。通过对比不同命令创建的文件,帮助初学者理解何时使用何种命令。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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?

Entering rails g model Test name:text in your command line will generate the following:

(1) A model file test.rb in your  models directory:

class Test < ActiveRecord::Base
end

(2) A migration file timestamp_create_tests.rb in your db/migrate directory:

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


 

Entering rails g resource Test name:text in your command line will generate the following:

(1) A model file test.rb in your  models directory:

class Test < ActiveRecord::Base
end

(2) A migration file timestamp_create_tests.rb  in your db/migrate directory:

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

(3) a tests_controller.rb file in your  controllers directory.  This controller will be an empty shell:

class TestsController < ApplicationController
end

 (4) resources :tests routes in your routes.rb file.

 



 

 

Entering rails g scaffold Test name:text in your command line will generate the following:

(1) A model file test.rb in your  models directory:

class Test < ActiveRecord::Base
end

(2) A migration file timestamp_create_tests.rb in your db/migrate directory:

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

(3) A tests_controller.rb file in your  controllers directory.  When a scaffold is generated, seven public methods and two private methods will be added to your controller:

(4) resources :tests routes in your routes.rb file.

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

转载于:https://www.cnblogs.com/gdpdroid/p/6872197.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值