牌語備忘録 -pygo

あくまでもメモです。なるべくオフィシャルの情報を参照してください。

牌語備忘録 -pygo

helper_method のメモ

コントローラのメソッドをビューから(ヘルパーも?)呼びたい時に使う

for example

app/controllers/products_controller.rb
class ProductsController < ApplicationController
  helper_method :sort_column, :sort_direction
  def index
    @products = Product.order(sort_column + ' ' + sort_direction)
  end
  
  private
  def sort_column
    params[:sort] || "name"
  end
  
  def sort_direction
    params[:direction] || "asc"
  end
end
app/helpers/application_helper.rb
module ApplicationHelper
  def sortable(column, title = nil)
    title ||= column.titleize
    direction = (column == sort_column && sort_direction == "asc") ? "desc" : "asc"
    link_to title, :sort => column, :direction => direction
  end
end
app/views/products/index.html.erb
<tr>
  <th><%= sortable "name" %></th>
  <th><%= sortable "price" %></th>
  <th><%= sortable "released_at", "Released" %></th>
</tr>