[Rails] Nested Attributes with Strong Parameters

在有些情況我們會需要做 Nested Form,這時候就需要將 Nested Form 的 Attributes 也加到 Strong Parameters 內。 以 order has_one info 為例 # order.rb class Order < ActiveRecord::Base has_one :info, class_name: "OrderInfo", dependent: :destroy end 在 order model 中以 accepts_nested_attributes_for »

[Rails] Rails 內如何操作 session

直接操作 session 這個 Hash 變數即可。 例如: 存 session[:current_user_id] = user.id 取 session[:current_user_id] 刪除 session[:current_user_id] = nil 清空 reset_session »

session 與 cookie 的差別

Cookie 當 Server 想要保存使用者的某些狀態,如登入資訊,會發送 Cookie 給 Client。 Cookie 是以明文的方式在網際網路上傳輸及在 Client 端電腦儲存,因此儘量避免使用 Cookie 儲存敏感的資料。 Session Session 與 Cookie 最主要的差異在於 Session 是保存在 Server 端,而不是 Client 端。但在使用 Session 仍然需要配合 Cookie 使用。 相較於 Cookie,Session 多用來儲存敏感 »

[Rails] before_action 使用時機

當有多個 Filter 時,Rails 是由上往下依序執行的。如果要加到第一個執行,可以使用 before_action。 常用於準備跨 action 共用的資料,以簡化程式碼;或是使用者權限驗證等。 另有 after_action 跑完 action 後才跑的 method 與 around_action 之前之後都跑 Ref: before_action »

[Rails] Strong Parameter

Rails 架構下,表單欄位直接對應到 Model 欄位,容易被有心人士猜測欄位進行竄改,產生資安問題。因此產生了 Strong Parameters 這套安全機制。 使用 Strong Parameters,只允許被 permit 的 params 可以通過,其餘的參數一律忽略,以防止猜測欄位的 hack。 Ref: ActionController::StrongParameters »

[Rails] Routing 的 Namespace

Namespace 是 Scope 的一種特定應用,這樣會影響整組 controller、網址 path、URL Helper 前置名稱 namespace :admin do resources :products end controller 會是 Admin::ProductsController 網址會是 /admin/products URL Helper 會是 admin_products_path »