ryanbillingsley
ryanbillingsley

Reputation: 215

Custom typecast method for ActiveRecord object's attribute

Is it possible to override the typecast of an attribute for an ActiveRecord object. For instance

class Project < ActiveRecord::Base

  def name.to_s
    #some logic to act on self.name
  end
end

I know I could do this with a helper, but just was curious if this was possible.

Upvotes: 0

Views: 972

Answers (1)

Cory
Cory

Reputation: 2538

If you're just wanting to manipulate what name returns...do this...

class Project < ActiveRecord::Base
  def name
    this_name = read_attribute(:name)

    # do some stuff with this_name

    this_name #return this_name
  end
end

Upvotes: 1

Related Questions