Linus Oleander
Linus Oleander

Reputation: 18127

Virtual attribute is being ignored

I'm having some strange problem with virtual attributes in rails.

Here is my example model.

class User < ActiveRecord::Base
  validates_presence_of :last_name
  validates_presence_of :first_name

  def clean!
    first_name = nil
    last_name = nil
  end
end

I can then do:

user = User.first
user.last_name # => "Smith"
user.clean!
user.save # => true
user.first_name # => "Smith"

Right now the first_name = nil part is ignored.
Anyone knows why?

Upvotes: 1

Views: 353

Answers (1)

DGM
DGM

Reputation: 26979

That's not a virtual attribute, it's just a method. It's not working because it doesn't know first_name is a method within the function, and thinks it is a variable. use:

def clean!
  self.first_name = nil
  self.last_name = nil
end

A virtual attribute, OTOH, is like a new table column that can be assigned to:

def full_name
  [first_name, last_name].join(' ')
end

def full_name=(name)
  split = name.split(' ', 2)
  self.first_name = split.first
  self.last_name = split.last
end

( virtual attribute code taken from http://railscasts.com/episodes/16-virtual-attributes )

Upvotes: 3

Related Questions