2012-01-08 150 views
0

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

如何在保存之前,但在验证之后访问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   
+0

后一些代码。 – 2012-01-08 20:59:34

+0

没有太多的帖子,但肯定:) – 1dayitwillmake 2012-01-08 21:32:32

回答

1

在一个实例变量存储应该工作:

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

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

你能详细解释一下这个答案(语义,这种方法背后的思考,为什么我的方法不起作用)? – 1dayitwillmake 2012-01-09 04:10:43

+0

我不确定你的方法不起作用。我测试了一个基本的after_validation实现,并在一个方法中调用了logger.debug(self.content),它的工作方式与您的预期相同。我唯一的猜测是,地理编码正在做一些事情,防止这些属性可见,但没有看到我不确定的方法。这就是说,创建一个实例变量来保存内容,而不管地理编码是在做什么,并直接访问它而不是直接在对象上的内容应该解决这个问题。 – josephrider 2012-01-09 04:46:23