Can't call request.remote_ip from object?


#1

class User

def update_metadata
self.update_attributes({:last_login_at => Time.now,
:last_known_up => request.remote_ip,
:last_known_user_agent =>
request.user_agent})
end

This does not work. It bombs out with:

undefined local variable or method `request’ for #User:0x1e146e0

But the request calls work in a controller such as:

@ip = request.remote_ip
@agent = request.user_agent

What is the proper way to get this data into my model?


#2

request are only readable in the controller. Take the ip address in the
controller and move it as a parameter into the model.

ip = request.remote_ip
@model.ip = ip

or put it into a hash (with all other parameters) and call the method in
the model.

Taylor S. wrote:

class User

def update_metadata
self.update_attributes({:last_login_at => Time.now,
:last_known_up => request.remote_ip,
:last_known_user_agent =>
request.user_agent})
end

This does not work. It bombs out with:

undefined local variable or method `request’ for #User:0x1e146e0

But the request calls work in a controller such as:

@ip = request.remote_ip
@agent = request.user_agent

What is the proper way to get this data into my model?


#3

Here’s the sort of thing you’re looking for:

class UserController
def some_action
@user = User.find(params[:id])
@user.update_metadata(:last_known_ip => request.remote_ip,
:last_known_user_agent => request.user_agent)
end
end

class User
def update_metadata(options = {})
options.reverse_merge!(:last_login_at => Time.now)
self.update_attributes(options)
end
end

This will update the request data only if you’re coming from a
controller, where there is request data.

Brent

Taylor S. wrote:

class User

def update_metadata
self.update_attributes({:last_login_at => Time.now,
:last_known_up => request.remote_ip,
:last_known_user_agent =>
request.user_agent})
end

This does not work. It bombs out with:

undefined local variable or method `request’ for #User:0x1e146e0

But the request calls work in a controller such as:

@ip = request.remote_ip
@agent = request.user_agent

What is the proper way to get this data into my model?


#4

Models should be blissfully unaware that they are attached to a web
app. For example, if you use your models from the console, or a rake
task, there is no web app, so if your models assume that a controller
exists you’re asking for trouble.

In this case, however, you can simply feed the :last_known_up
and :last_known_user_agent to your model this way:

class UserController
def some_action
@user = User.find(params[:id])
@user.update_metadata(:last_known_up =>
request.remote_ip, :last_known_user_agent => request.user_agent)
end
end

class User
def update_metadata(options = {})
options.reverse_merge!(:last_login_at => Time.now)
self.update_attributes(options)
end
end

Brent

On Feb 9, 11:34 am, Taylor S. removed_email_address@domain.invalid