Jryl
Jryl

Reputation: 1156

How to write a virtual attribute's getter and setter methods?

My product model belongs to a telephone and I wanted to know how I would join both together for a virtual attribute. I can create a product and can find or create the telephone by it's number with the code below.

Product < ActiveRecord::Base
  attr_accessible :name, :telephone_number
  belongs_to :telephone

  def telephone_number
    telephone.try(:number)
  end

  def telephone_number=(number)
    self.telephone = Telephone.find_or_create_by_number(number) if number.pr....
  end

Now for getter method I put:

  def product_with_number
    [name, telephone_number].join(',')
  end

But I'm not sure what's next or if this is what I'm getting at. I'm trying to make a single field where I can type in:

Cow's Beef Jerky, 555-323-1234

Where the comma seperates the product name and telephone and if the telephone number is new, it will create it. Am I on the right track, what next?

Thanks.

Upvotes: 0

Views: 812

Answers (1)

RadBrad
RadBrad

Reputation: 7304

You need a corresponding setter:

def product_with_number=(str)
  parts = str.split(',')
  self.telephone_number = parts[0]
  self.name = parts[1]
end

Then all you'd do is something like this:

@p = Product.New
@p.product_with_number = "Cow's Beef Jerky, 555-323-1234"
@p.save

Upvotes: 1

Related Questions