在rails入門博客中遇到的問題

1,新建一個資源數據庫

Rails.application.routes.draw do
 
   resources :articles
 
   root 'welcome#index'
end

2,執行生成rest風格的的動做瀏覽器

$ bin/rake routesapp

      Prefix Verb   URI Pattern                  Controller#Actionspa

    articles GET    /articles(.:format)          articles#indexrest

             POST   /articles(.:format)          articles#createcode

 new_article GET    /articles/new(.:format)      articles#neworm

edit_article GET    /articles/:id/edit(.:format) articles#edit對象

     article GET    /articles/:id(.:format)      articles#show資源

             PATCH  /articles/:id(.:format)      articles#update字符串

             PUT    /articles/:id(.:format)      articles#update

             DELETE /articles/:id(.:format)      articles#destroy

        root GET    /                            welcome#index

3,一段輸出代碼

render plain: params[:article].inspect

inspect相似於toString,就是把參數的信息打印在頁面上

render 方法接受一個簡單的 Hash 爲參數,這個 Hash 的鍵是 plain,對應的值爲 params[:article].inspectparams 方法表示經過表單提交的參數

4,新建模型

$ bin/rails generate model Article title:string text:text

5,執行數據庫遷移,就是相似於把對象對應到數據庫中的相應表中

db:migrate

6,用 render 方法才能在保存失敗後把 @article 對象傳給 new 動做的視圖。渲染操做和表單提交在同一次請求中完成;而 redirect_to 會讓瀏覽器發起一次新請求

7,數據驗證

@article.errors.any? 檢查是否有錯誤,若是有錯誤,使用 @article.errors.full_messages 顯示錯誤

pluralize 是 Rails 提供的幫助方法,接受一個數字和字符串做爲參數。若是數字比 1 大,字符串會被轉換成複數形式

<%= pluralize(@article.errors.count, "error") %>這段代碼顯示的是一共有幾個錯誤的信息

8,在app/models/article.rb中寫入校驗的規則

class Article < ActiveRecord::Base
   validates :title , presence: true ,
                     length: { minimum: 5 }
end

presence:true;不能爲空。length:{minimum:5}最少多少個字

相關文章
相關標籤/搜索