Skip to content
This repository has been archived by the owner on Apr 21, 2024. It is now read-only.

Latest commit

 

History

History
69 lines (55 loc) · 1.32 KB

README.md

File metadata and controls

69 lines (55 loc) · 1.32 KB

rails CRUD practice

rails new {name}

  1. 建立專案
    • $ rails new {project_name}
    • $ cd {project_name}

Book (CRUD)

  1. 建立路徑

    • in routes.rb
      • resources :books
  2. 建立 Controller

    • $ rails g controller Books
  3. 建立 actions

  4. 建立 templates

  5. 建立 Model

    • $ rails g model Book title content:text price:integer
      • title:string
      • content:text
      • price:integer
  6. 建立 _form

<%= form_for book do |f| %>
  書名
  <%= f.text_field :title %>
  內容
  <%= f.text_area :content %>
  價格
  <%= f.number_field :price %>
  <%= f.submit %>
<% end %>
  1. 建立新增頁面 new.html.erb
<h1>新增一本書</h1>
<%= render 'form', book: @book %>
  1. 建立 Controller 內的 action : index new create show edit delete

    • 驗證 app/models/book.rb
    validates :title, presence: true
    
    • 資料清洗 app/controllers/books_controllers.rb
    def book_params
      params.require(:book).permit(:title, :content, :price)
    end
    
    • 抽出尋找特定id的方法
    before_action :find_book, only: [:show, :edit, :update, :destroy]
    private
    def find_book
      @book = Book.find_by(id: params[:id])
      redirect_to books_path if @book.nil?
    end