當我們在Rails說CRUD的時候,代表我們通常是在做下面四件事情(新增,讀取,更改與刪除)
CRUD = create , read , update, delete
app/views/articles/new.html.erb 新增內容
<h1>新增文章</h1>
<%= form_with(model: @article, data:{ turbo: false }) do |f| %>
<div>
<%= f.label :title, '標題' %>
<%= f.text_field :title %>
</div>
<div>
<%= f.label :content, '內文' %>
<%= f.text_area :content %>
<%= f.submit %>
</div>
<% end %>
點擊完save後,會有錯誤訊息"No route matches [POST] "/articles/new""
這告訴我們目前routes中並沒有 post action 會對應到 "/articles/new" 這條路徑
config/routes.rb
新增 : post "/articles", to: "articles#create"
Rails.application.routes.draw do
# Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html
# get "/", to: "articles#index"
root "articles#index" # 首頁的新寫法
get "/articles", to: "articles#index"
get "/articles/new", to: "articles#new"
post "/articles", to: "articles#create"
end
rails g model Article title content:text
建立一個model, 名稱是Article, 欄位1 : title⇒ 字串 , 欄位2 : content:text
執行完後會產生一個db檔
t.int :id
class CreateArticles < ActiveRecord::Migration[7.0]
def change
create_table :articles do |t|
t.string :title
t.text :content
t.timestamps
end
end
end
rails db:migrate
rails db:migrate
class ArticlesController < ApplicationController
def index
end
def new
@article = Article.new
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to "/articles", notice: "文章新增成功"
else
# 沒有新增成功時拿new.html.erb 渲染
render :new
end
end
def article_params
params.require(:article).permit(:title, :content)
end
end
class Article < ApplicationRecord
validates :title, presence: true
end
<!DOCTYPE html>
<html>
<head>
<title>WretchClone</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
<%= javascript_importmap_tags %>
</head>
<body>
**<%= flash[:notice] %>
<%= flash[:alert] %>**
<%= yield %>
</body>
</html>
不成功的時候會把區塊加上 div :field_with_errors 造成跑版
⇒ 改成display :inline
app/assets/stylesheets/application.css
.field_with_errors {
display: inline;
}
.field_with_errors input {
border: px solid red;
}