用新建scaffold的方法 创建一个带CRUD增删改查操作的 小WEB项目

    技术2022-05-20  35

    【1】新建一个Rails项目,这个就不多说了,我们把这个项目取名为ScaffoldTest

    【2】配置好config/database.yml文件,也就是配置好数据库,当然之前要先建好相应的数据库

    【3】新建好后,用generate工具,或在命令行敲下面的代码:

     $ script/generate scaffold Contact name:string email:string

    这是核心命令,意思创建一个模型层对象Contact,有两个字段,一个为name(数据类型为string),另一个为email(数据类型为string)

    【3】如果不出意外的话,那就应该成功了,到app文件夹下的Controller、Model、View三个文件夹看看吧,CRUD已经有了,而且出现了四个模板视图:edit.html.erb、index.html.erb、new.html.erb、show.html.erb

    【4】运行命令 $rake db:migrate,将db文件夹下生成的代码运行一遍,将该表及其字段相应的在数据库中创建

    【5】重启服务器,在浏览器看看吧!

    生成的 contacts_controller.rb如下:

    class ContactsController < ApplicationController # GET /contacts # GET /contacts.xml def index @contacts = Contact.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @contacts } end end # GET /contacts/1 # GET /contacts/1.xml def show @contact = Contact.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @contact } end end # GET /contacts/new # GET /contacts/new.xml def new @contact = Contact.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @contact } end end # GET /contacts/1/edit def edit @contact = Contact.find(params[:id]) end # POST /contacts # POST /contacts.xml def create @contact = Contact.new(params[:contact]) respond_to do |format| if @contact.save flash[:notice] = 'Contact was successfully created.' format.html { redirect_to(@contact) } format.xml { render :xml => @contact, :status => :created, :location => @contact } else format.html { render :action => "new" } format.xml { render :xml => @contact.errors, :status => :unprocessable_entity } end end end # PUT /contacts/1 # PUT /contacts/1.xml def update @contact = Contact.find(params[:id]) respond_to do |format| if @contact.update_attributes(params[:contact]) flash[:notice] = 'Contact was successfully updated.' format.html { redirect_to(@contact) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @contact.errors, :status => :unprocessable_entity } end end end # DELETE /contacts/1 # DELETE /contacts/1.xml def destroy @contact = Contact.find(params[:id]) @contact.destroy respond_to do |format| format.html { redirect_to(contacts_url) } format.xml { head :ok } end end end

    【PS】如果此命令出错的话,可能是因为Rails的版本问题,可以参考这里:

    http://topic.csdn.net/u/20070513/22/5931d7c7-7451-4cc3-9dc5-ca3afbb0cae8.html?241961724

     


    最新回复(0)