在回调中访问非活动记录属性before_save



在我看来,我使用<%= f.text_field :latlon %>来编辑latlon属性(而不是ActiveRecord列)。 保存时,我想解析latlong并将其拆分为lat并在before_save回调中lon

我不知道如何在回调中访问latlon变量的参数。 我已经尝试过self.latlong但这调用了与latlon属性相同的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,对吗?

最新更新