Rails saves an IP address every time it is requested to create / update

I would like to do the following:

define before_filter in application.rb that retrieves the user's IP address and stores it anywhere, preferably in a session.

define two before filters in all my models as before_create and before_update, which add the user's current IP address to the object to be saved.

Problem: I cannot access session[] nor env[] in the model. Can someone help with a standard solution that I don't know yet?

Relationship jason

+4
source share
5 answers

Try it. In your user model, add a class attribute attribute

 cattr_accessor :current_ip 

In the application controller add:

 before_filter :set_current_ip protected def set_current_ip User.current_ip = request.env['REMOTE_ADDR'] end 

Then in your model, you can just call User.current_ip

We are doing something similar to pass the current_user object.

+5
source

You are having problems with what you want because Rails does not allow you to have access to session information in your models. This is a classic separation of issues with MVC. Models are designed to work regardless of your other levels, and you will be grateful to them when you start to do something using Rake or other system tasks where you will not have a session.

 cattr_accessor :current_ip 

is a terrible approach. This is a hack, and it should be clear why. Yes, it may work, but this is the wrong approach to this problem.

Since you are tracking the β€œwho” has done the β€œwhat” by their IP, the logical place for this happens in the controller layer. There are several approaches, including using CacheSweepers as auditors, as described in the Rails Recipes book. CacheSweepers can monitor models, but also have access to all controller information. Using the ditry attributes in the rail model, you can see exactly what has changed.

 @user = User.find_by_login "bphogan" @user.login = "Brian" @user.save @user.changed => ["login"] @user.changes => {"login"=>["bphogan", "brian"]} @user.login_was => "bphogan" 

Combine this with the session information you have, and you have a pretty amazing audience.

Does it help?

+1
source

If you want to keep the IP address in the session, you can create a before filter in the applicationController. Similarly, for each action, a filter is called and ip is saved.

0
source

authlogic is a plugin for managing user logins / sessions, etc., it has a built-in option for tracking user IP addresses

0
source

What you really need is a plugin for the version. I suggest taking a look at one of the great solutions at http://ruby-toolbox.com/categories/activerecord_versioning.html

0
source

All Articles