request.remote_ip from the model?

0

How can I get the IP from the model, when I assign it a value that saves only null.

Example:

class User < ApplicationRecord

  before_create :asignar_ip

  def asignar_ip
    self.ip_inicial = request.remote_ip
  end

end

Any ideas?

Update

I'm working with the gem devise and therefore I do not have access to the users controller.

    
asked by rrg1459 21.11.2017 в 16:30
source

1 answer

2

You could generate your own registry controller (which inherits the one from Devise ) and define / modify the action create of Devise , in which you can update that attribute ; for example:

# app/controllers/registrations.rb

class RegistrationsController < Devise::RegistrationsController
  def create
    super
    resource.update!(ip_inicial: request.remote_ip)
  end
end

What you are doing is simply redefining the action create to have the normal behavior of Devise (for that it is super ) but before finishing the action, take the object resource (ie user) generated and add the attribute ip_inicial .

Now you should only indicate in your routes.rb file that Devise use this new driver:

# config/routes.rb

# ...
devise_for :users, controllers: { registrations: "registrations" }

Previous response

The request object is only available in the controller, so you should read its value there and then assign it to an attribute of the model.

Since you want to assign the value of ip_inicial when creating the object (i.e. User ), I recommend you to pass it as one more parameter of your model when creating it; for example, assuming that your model User had the attributes name , email e ip_inicial , you would do the following in the controller:

User.create(name: "Gerry", email: "[email protected]", ip_inicial: request.remote_ip)

And in your model User it would not be necessary to put additional callbacks or methods .

    
answered by 21.11.2017 / 16:53
source