2

I tried the following:

In user.rb:

before_create :record_sign_up_ip

protected
def record_sign_up_ip
  self.sign_up_ip = current_sign_in_ip
end

Unfortunately, although current_sign_in_ip has my correct local ip of 127.0.0.1, sign_up_ip remains as nil. How can I easily get the IP of someone signing up? Normally I would put this in the create controller, but with Devise, there is no controller for User.

Raj
  • 22,346
  • 14
  • 99
  • 142
at.
  • 50,922
  • 104
  • 292
  • 461
  • You can override/supplement the controller used by Devise as noted here http://stackoverflow.com/questions/3546289/override-devise-registrations-controller – nachbar Jan 22 '14 at 05:39

2 Answers2

3

Override the controller used by Devise as noted at Override devise registrations controller

As modified from that post, create app/controllers/users/registrations_controller.rb:

# app/controllers/users/registrations_controller.rb
class Users::RegistrationsController < Devise::RegistrationsController

  def create
    params['user']['sign_up_ip'] = request.env['REMOTE_ADDR']   
    super
  end

end 

Also modified from that post, to use that controller:

# app/config/routes.rb
devise_for :users, :controllers => {:registrations => "users/registrations"}

You also need to make sign_up_up accessible (for Rails 3):

# app/models/user.rb
  attr_accessible :sign_up_ip
Community
  • 1
  • 1
nachbar
  • 2,643
  • 1
  • 24
  • 34
  • I don't want `sign_up_ip` to be mass assignable. Any way to modify the `User` object before it gets saved? – at. Jan 22 '14 at 08:02
  • In that case, I would probably copy over the entire create method that you are overriding from Devise::RegistrationsController at https://github.com/plataformatec/devise/blob/master/app/controllers/devise/registrations_controller.rb and modify it to manually add the IP address without making sign_up_ip mass assignable. – nachbar Jan 23 '14 at 00:46
  • Another option would be to use attr_readonly -- that way, the field will be able to be assigned when the record is created, but mass assignment will not be permitted to change the value. Since the code above sets sign_up_ip when the record is created, it will not be possible to change it. I think this is a better option, and have edited my answer to change attr_accessible to attr_readonly. – nachbar Jan 24 '14 at 00:31
  • Nevermind about attr_readonly -- it appears that attr_readonly does not work in conjunction with other fields defined as attr_accessible -- http://stackoverflow.com/questions/11383061/rails-attr-readonly-doesnt-work However, that post also shows how to prevent changes to the sign_up_ip by implementing a validation that only runs on update. – nachbar Jan 24 '14 at 00:40
0

In your user model,

def init
    self.sign_up_ip = current_sign_in_ip
end
Raj
  • 22,346
  • 14
  • 99
  • 142
  • When I tried that, init does not seem to be called during User creation. Is there additional configuration required? – nachbar Jan 22 '14 at 06:31