Rails - 属性更改检测 - 未定义方法`ip_address_changed?'不适用于Heroku

时间:2015-03-08 15:17:40

标签: ruby-on-rails heroku geolocation rails-geocoder

在rails中我的用户模型中有以下代码。当我运行我的开发服务器时它工作正常,并且根本不会抛出任何错误。推到Heroku后我得到了错误

NoMethodError (undefined method `ip_address_changed?' for #<User:0x007ff3da78d3d8>): app/controllers/users_controller.rb:55:in `update'  

在我的用户模型中,我有ip_address可以更新。根据Ryan bates的文档和Railscasts,我可以使用列名:ip_address,然后添加_changed?在末尾。所以,我试过了:if => :ip_address_changed?这一行 我怎样才能让它在Heroku上工作,我做的事情是不正确还是现在已被弃用?

  geocoded_by :ip_address
  reverse_geocoded_by :latitude, :longitude, :address => :location do |user, results|
    #further populate the model based on the :location
    if geo = results.first
      user.country = geo.country_code
      user.state = geo.state
      user.city = geo.city
    end
  end # end block reverse geocoded
  after_validation :geocode, :reverse_geocode, :if => :ip_address_changed?

我可以删除:if => :ip_address_changed?,但这会为google api产生不必要的流量。

1 个答案:

答案 0 :(得分:0)

我找到了另一个Ryan Bates视频的答案,该视频涵盖了属性的跟踪变化。 http://railscasts.com/episodes/109-tracking-attribute-changes

原因是我在创建时显然绕过了二传手!方法或@user.update_attributes!(user_params)。这意味着它无法跟踪更改,除非我将其切换到正常@user.save而没有爆炸!

我很快就会这样做,但是现在Ryan Bates在视频中提到的解决方法是告诉我我正在更改模型上的属性,或者它会因为我的逻辑需要而改变。

所以在我的控制器中,在我的#update动作中我现在有了这个。 在Heroku上测试它现在有效。

  def update
    @user = User.find(session[:user_id])

    @user.ip_address = request.remote_ip
    @user.ip_address_will_change! #by passing setter method so the model will work

    # save data
    # this line also includes newly uploaded photos as well as profile info
    @user.update_attributes!(user_params)
    redirect_to users_path
  end