Rails モデルクラスにユティリティ関数を定義する

2012年8月28日 Posted by PURGE

Userモデル内で、属性がlast_nameとfirst_nameで、別々に定義されている場合、user_name のように、関数定義をしておくと便利。
また、DBにマスタとして定義していないモデルの属性もsexのように定義すると便利。

#coding: utf-8
class User < ActiveRecord::Base
  #
  # 属性情報
  # 
  attr_accessible :first_name, :last_name, :sex_cd

  def user_name
    attributes["last_name"] + attributes["first_name"]  
  end

  def sex
    {1 => "男性", 2 => "女性"}
  end
end

下記のように呼べる。

<%= user.user_name %>
<%= user.sex[user.sex_cd] %>

基本的なところで、ハマっていたのだが、モデルクラスに、#coding: utf-8を指定しないと変なエラーにハマる。気を付けよう。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です