coding with alpaca 23- 24
Aug 9, 2017 · 2 min read
新增表單
get '/stores/new' 是跟這個網址要資料
post 是送資料到這個網址form 表單
<form action="/stores" method="post">
<!-- 防駭客token -->
<input type="hidden" name="authenticity_token" value="<%=
form_authenticity_token %>"> <!-- 給人看的 -->
<label>店家名稱</label> <!-- 給電腦看的 -->
<input type="text" name="name"> <!-- 按鈕 -->
<input type="submit" value="送出"></form>
送出之後

因為 route 沒有定義 post 到 '/stores' 之後要做什麼csrf attack
原來 params 是個變數
stores_path == '/stores'stores controller
def new
@store = Store.new
enddef create
store = Store.new store.name = params[:name]
store.description = params[:description]
store.phone = params[:phone]
store.address = params[:address] store.save
redirect_to '/stores'
end
rake routes
Prefix Verb URI Pattern Controller#Action
root GET / pages#homepage
stores GET /stores(.:format) stores#index
stores_new GET /stores/new(.:format) stores#new
POST /stores(.:format) stores#create原本
redirect_to 'stores_path'重構
redirect_to stores_path原本
<form action="/stores" method="post">
<input type="hidden" name="authenticity_token" value=" <%=
form_authenticity_token %> ">
<label>店家資訊</label>
<input type="text" name="name"><br> <label>簡單描述</label><br>
<textarea name="description" cols="30" rows="5">
</textarea><br> <label>電話</label>
<input type="text" name="phone"><br> <label>地址</label>
<input type="text" name="address"><br> <input type="submit" value="送出">
</form>
重構
<form action="/stores" method="post">
<input type="hidden" name="authenticity_token" value=" <%=
form_authenticity_token %> ">
<label>店家資訊</label>
<input type="text" name="store[name]"><br> <label>簡單描述</label><br>
<textarea name="store[description]" cols="30" rows="5">
</textarea><br> <label>電話</label>
<input type="text" name="store[phone]"><br> <label>地址</label>
<input type="text" name="store[address]"><br> <input type="submit" value="送出">
</form>
顯示結果是個大 hash 包小 hash
{
"authenticity_token":"+D2XyQtNHk7QnSdEVcA/Sq86eupBbJE01KOfUjyh1XM/9+CypAkdWrKD4OAAfayTpOXzdxs9QFsRWNuEYmv+Jw==","store": {
"name": "fdfsdf",
"description": "fsdfdsf",
"phone": "fdsfs",
"address": "fsdfsd"
},"controller": "stores",
"action": "create"
}

不能把使用者輸入的東西都塞進實例變數存起來,會有資安問題
solution
privatedef stores_params
params.require(:store).permit(:name, :description, :address,
:phone)
end
解決一切的 form helper
<%= form_for @store do |f| %>
<%= f.label :name, "店家資訊" %>
<%= f.text_field :name %><%= f.label :description, "簡短描述" %>
<%= f.text_area :description %><%= f.label :phone, "電話" %>
<%= f.text_field :phone %><%= f.label :address, "地址" %>
<%= f.text_field :address %><%= f.submit '送出' %><% end %>
form fo 表單
看完 course 24

