picardo
picardo

Reputation: 24886

How to use ActiveRecord callbacks to assign field values before save?

I'm wondering how I can use callbacks to assign values to the database fields, which are processed out of a virtual attribute field.Example:

  field :houseno, :type => String
  field :street, :type => String

  attr_accessor :address

My attempt at this seems to be unsuccessful. Here is what I have:

  before_validation :assign_fields


  def assign_fields
    if @address
      @houseno = @address.match(/^(\d+-?(\d+)?)\W*(.*)/)[1]
      @street = @address.match(/^(\d+-?(\d+)?)\W*(.*)/)[3]
    end
  end

And I keep getting this error:

undefined method `houseno' for Building:0x0000010488f108

Upvotes: 1

Views: 762

Answers (1)

markquezada
markquezada

Reputation: 8515

Have you tried:

write_attribute(:houseno) = @address.match(/^(\d+-?(\d+)?)\W*(.*)/)[1]

or

self.houseno = @address.match(/^(\d+-?(\d+)?)\W*(.*)/)[1]

Upvotes: 2

Related Questions