As part of my project, I need to store IP address for every object
that was created.
User
Topic
Payment
and more...
Now all these records have the following attribute in their table
called "ip_address_on_create".
One way to do this is to put this code everywhere in the controllers:
user.ip_address_on_create = request.remote_ip ,.... and so
forth.
Now to conform to DRY (don't repeat yourself), I see the mechanism:
after_create (model) and after_filter ( controller). I am not
really sure how to tie this thing together. Would appreciate any tips
or Ruby-Fu .
Have a look at active_record::observers and wrap the save method with
an update to the ip address. Declare a class level variable in
application.rb with a before_filter that populates the IP into the
variable (and subsequently used by the observer).
Basically... the class variable is shared by all instances of the
controller in question spawned by the Rack server process.
Multithreaded Rails handles multiple requests simultaneously, and thus
multiple simultaneous instances of the controller. Two requests come
along, one from 1.1.1.1, then one from 2.2.2.2 immediately after.
before_filter from 1.1.1.1's controller instance sets class variable
accordingly, then before_filter from 2.2.2.2's instance overwrites the
variable. Controller instance from 1.1.1.1 now uses 2.2.2.2's IP, and
shinanagins ensue.