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

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

[ruby]
#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
[/ruby]

下記のように呼べる。
[ruby]
<%= user.user_name %>
[/ruby]

[ruby]
<%= user.sex[user.sex_cd] %>
[/ruby]

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

This entry was posted in Rails, Ruby, 技術情報. Bookmark the permalink.

コメントを残す

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