在after_validation块中访问模型中的属性

时间:2012-01-08 20:56:54

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1

我试图在模型的after_validation回调中修改模型的属性,但是所有@attributes都返回nil,因此方法失败。

如何在保存之前访问ActiveRecord的@attributes,但在验证之后。 我试图从类本身的方法中访问它。

    class Business < ActiveRecord::Base
            attr_accessible :latitude, :longitude
            geocoded_by :address
            after_validation :geocode

            # Returns a human readable address from our various fields
            def address
                # All of these are nil when this gets called, from the geocode block which gets called by after_validation
                [self.street + self.street2, self.city, self.state].compact.join(', ')
            end
    end         

1 个答案:

答案 0 :(得分:1)

存储在实例变量中应该有效:

after_validation {|x| @this = x; geocode}

def address
  [@this.street + @this.street2, @this.city, @this.state].compact.join(', ')
end