开发者

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

开发者 https://www.devze.com 2023-02-02 21:59 出处:网络
I\'m wondering how I can use callbacks to assign values to the database fields, which are processed out of a virt开发者_高级运维ual attribute field.Example:

I'm wondering how I can use callbacks to assign values to the database fields, which are processed out of a virt开发者_高级运维ual 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


Have you tried:

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

or

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号