假设我有一个方法,它结合了几个地址字段,如下所示:
def address
"#{street_address}, #{city}, #{state}, #{postal_code}, #{country}"
end
如何扩展方法以允许检查是否有任何字段已更改?基本上,我希望能够做到以下几点:
after_validation :geocode, :if => :address.changed?
我的模型如下:
class Place < ActiveRecord::Base
attr_accessible :street_address, :city, :state, :postal_code, :country, :latitude, :longitude, :geocode_type
geocoded_by :address
after_validation :geocode#, :if => :address.changed?
def address
"#{street_address}, #{city}, #{state}, #{postal_code}, #{country}"
end
end
还是有更好的方法可以一起做到这一点吗?
答案 0 :(得分:6)
def address_changed?
attrs = %w(street_address city state postal_code country)
attrs.any?{|a| send "#{a}_changed?"}
end
答案 1 :(得分:2)
有点笨重......
def address_changed?
street_address_changed? || city_changed? || state_changed? || postal_code_changed? || country_changed?
end