1

I am using Ruby on Rails 3 and I am tring to do some like this in my model file

if request.headers["CONTENT_LENGTH"]
  ...
end

but I get this error:

NameError (undefined local variable or method `request' for #<User:0x00...>):

So, is it possible to use the 'request' method in a model? If so, how?

4
  • If you can access the request from the model, you still shouldn't. What's the actual problem you're trying to solve? There is undoubtedly a better way to solve it in rails.
    – Don Roby
    Jan 29, 2011 at 15:33
  • I am trying to validate a file upload using a CUSTOM validation method in the model. See also this: stackoverflow.com/questions/4837014/…
    – user502052
    Jan 29, 2011 at 15:48
  • @user502052: but why do it in the User model?
    – tokland
    Jan 29, 2011 at 16:12
  • Because there I have declared all my validation methods.
    – user502052
    Jan 29, 2011 at 16:25

3 Answers 3

2

No, because the request is only available in controllers and view code. From a design point of view you're ill advised to use the request within model code, but let's say you want to do something with the request on a particular instance of your User, just create a method for it:

class User
  ...
  def has_a_request?(request)
    raise ArgumentError if(request.blank? || !request.respond_to(:headers))
    if(request.headers["CONTENT_LENGTH"] # Does it really have CONTENT_LENGTH btw?
      puts "#{self.username} got a request with content length"
      return true
    else
      puts "#{self.username} didn't get a request with content length"
      return false
    end
  end

And then elsewhere in your application:

User.has_a_request?(request)
1
  • I'd probably decouple it a little and instead of sending the whole request (a model looking into requests is kind of weird), send only whatever the method really needs to check. But the OP question is so terse that it's impossible to do it, so this answer is ok.
    – tokland
    Jan 29, 2011 at 16:07
0

Is not good app design to use the request object in the method, but if you do absolutely need it you can do :

class User
  def a_method request
  end
end

class UserController
  def index
    User.find(params[:user]).a_method request
  end
end
0

Extract relevant data from the request object in your controller, then pass them on to the model -- either by setting attributes on an instance of it or by passing them as parameters to a method call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.