Can't call request.remote_ip from object?

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?

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?

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?

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. [email protected]