在我看来,我使用<%= f.text_field :latlon %>
来编辑latlon
属性(而不是ActiveRecord列)。 保存时,我想解析latlong
并将其拆分为lat
并在before_save
回调中lon
。
我不知道如何在回调中访问latlon
变量的参数。 我已经尝试过self.latlong
但这调用了与lat
和lon
属性相同的attr_reader
。
我知道我可以在控制器中做到这一点,但是,这是模型逻辑,不是吗?
#app/models/bla.rb
class Bla < ActiveRecord::Base
attr_accessible :name, :lat, :lon, :latlon #but latlon is not an ActiveRecord Attribute
before_save :foo
def latlon
"#{lat}, #{lon}"
end
attr_writer latlon
private
def foo
self.lat = # regex that parse latlon
self.lon = # regex that pase coors
end
end
您可以重写赋值方法来执行所描述的操作。这样做的好处是单元测试更快/更容易。
def latlon=(new_value)
# do work to split and assign
end
我认为你可以attr_writer latlon
用
def latlon=(latlon)
self.lat = # regex that parses lat from latlon
self.lon = # regex that parses lon from latlon
end
也许不要让 :lat 和 :lon 成为attr_accessible
的一部分,因为它们永远不会被大规模分配,即从 params
数组中分配。 从控制器传递params
将包含latlon
值(格式正确)。
我认为在这种情况下你不需要before_save
。
模型应该可以访问您可以使用的实例变量@latlon
,对吗?