Source: http://asciicasts.com/episodes/16-virtual-attributes
I’d like to achieve a similar setup as below, but in CakePHP and where the virtual attributes are created using code, not SQL (as documented at http://book.cakephp.org/view/1070/Additional-Methods-and-Properties#Using-virtualFields-1590).
class User < ActiveRecord::Base
# Getter
def full_name
[first_name, last_name].join(' ')
end
# Setter
def full_name=(name)
split = name.split(' ', 2)
self.first_name = split.first
self.last_name = split.last
end
end
As you’ve rightly mentioned, virtualFields are used to create extra attributes for models using SQL. For generating fields using code, you should try the
afterFindmethod:You can read more on this from the book here. I’d assume you’ll have to test this a little further, and probably include the
afterFindmethod’s second parameter$primary.EDIT: I just realized that another way of doing this would be to include such functions directly in your model:
And there’s your getter!