PinoyTech.org

CodeIgniter, Kohana, Mootools, jQuery and CSS

Create a Virtual field in Rails

Posted by teejay on March 9, 2011

Being new to Rails, I didn't know how to create a virtual field. In CakePHP you'd need to create a public property and assignment will be there. However, in Rails, this isn't the way.

  def full_name
    [self.first_name, self.last_name].compact.join(" ")
  end

This is especially useful like above when you don't have a first_name and last_name, it makes sense that when you need a full_name, you can just do it in the model instead of doing it everywhere you need full_name.

Categories: How To

Tags: rails

No Comments

Comments are not allowed