views:

233

answers:

3

I have an existing app that has many, many models. I'd like to log the IP address of the user that created them with the primary purpose being a way to help weed out spammers or other abusive users (if I don't know what IP address(es) they are using, I can't block it). I would need to keep track of these over time as users may access from home, the office, their phone, etc. and I'd want to see usage patterns. It also might be kind of fun to map out where users are visiting from or something, but any side-effects are purely thought-stuff at this time.

We use the cookie-based method of storing user sessions.

I can think of two ways of doing this (I'll create them as replies so people can vote):

  1. Add IP address attribute to every model, and pass that in
  2. Some sort of Logger model that is called with an observer or after_save callback

Thoughts? Are there better ways? Plugins that do this? Thanks!!

A: 

Add IP address attribute to every model, and pass that in

Pros:

  • Conceptually simple. There's an attribute and I can easily see that posting 123 was uploaded by user 222 w/IP 123.123.123.123

Cons:

  • Requires me to touch/re-code every model & every Model.create (it uses the rails idiom of the Model.create params[:model], so I'd just tack on request.address). This is a LOT of work. Lots of tests will have to be re-written
  • If I ever move to IPv6, this will fail (if the models are expecting IPv4 addys)
Matt Rogish
+1  A: 

Some sort of Logger model that is called with an observer or after_save callback

Pros:

  • Can be done via an observer, so models don't even need to be aware
  • All the logging takes place in one model/database table, so it's easy to query and run reports later

Cons:

  • How the heck do I get the IP address without modifying every Model.create to pass it in? I'd have to break MVC theory, which I am willing to do, but I don't really know how
Matt Rogish
+1  A: 

I would use a polymorphic association for this, and then you can apply it to all your models that need to be tracked. That keeps the messyness of adding an IP address column to every model to a minimum and will dramatically cut down on the amount of duplication across your codebase. Then going the observer route is probably the easiest way to hook up to your models.

Scott Miller