[Note] Rails近日專案實作筆記
統一使用simple_form
原本使用很混亂,有時候在post表單中會用simple_form,而在搜尋的欄位卻用form_tag,後來發現其實simple_form也可以不用對應controller直接送網址,例如:
<%= simple_form_for "" ,url: whatever_path , :method => :get do |f| %>
<div class="col-md-10">
<%= f.input :address, label: false, placeholder: '地址' ,:autofocus => true, input_html:{ value: params[:address]} %>
</div>
<div class="col-md-2">
<%= f.submit "搜尋", class: "btn btn-primary" ,data:{ disable_with: "搜尋中" }, name: nil %>
</div>
<% end %>
取得目前網址
會想要用到目前網址主要是因為各個頁面內部的查詢條件及表單,每次送出其實是原本的頁面,但卻要在明確指出一次path,覺得很煩,所以找到以下取代方式
# 絕對URL:
request.original_url
# 相對URL:
request.fullpath
因為這寫法實在太不rails了,所以把它寫成helper
def current_path
request.fullpath
end
controller名稱 與 model名稱 的轉換
#####tableize
'fancyCategory'.tableize
# => "fancy_categories"
#####classify
'fancy_categories'.classify
# => "fancyCategory"
圖片從img改用css3的background url
因為常常會有圖片失效的狀況,這邊直接用css3避免掉叉燒包的狀況
<div style="
background: url(xxx.png) no-repeat;
background-size: 50px Auto;
height: 50px;
width: 50px" >
</div>
這邊用style舉例,通常是寫class
動態顯示404、500頁面
###1) 建立controller
$ rails generate controller errors not_found internal_server_error
###2) 調整controller
class ErrorsController < ApplicationController
def not_found
render(:status => 404)
end
def internal_server_error
render(:status => 500)
end
end
###3) 設定route
match "/404", :to => "errors#not_found", :via => :all
match "/500", :to => "errors#internal_server_error", :via => :all
###4) 告訴rails我們要自己處理錯誤頁面
# [path] config/application.rb
config.exceptions_app = self.routes
###5) 刪除原本的public下的404及500網頁
rm public/{404,500}.html
###6) 調整你的View
- not_found.html.erb
- internal_server_error.html.erb
一般來說他們會被render在layout/application.html.erb之中 照慣例,你也可以自行建立一個專用的layout/error.html.erb來統一錯誤訊息的版型
###7) 進行測試 你可以使用 http://localhost:3000/404 或 http://localhost:3000/500 來測試
其它頁面若也想測試的話,可以在developmant.rb把錯誤訊息先暫時關閉
# [path] config/environments/development.rb
config.consider_all_requests_local = false
判斷layout方式
有時候需要依據條件來判斷layout
class UsersController < ApplicationController
layout :choose_layout
def choose_layout
if action_name == "edit"
"application"
else
"login"
end
end
end
array to hash
參考
留言