是否可以使用“请求”?模型中的方法?

发布于 2024-10-15 01:51:08 字数 319 浏览 2 评论 0原文

我正在使用 Ruby on Rails 3,并且尝试在我的 model 文件中执行类似的操作

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

,但出现此错误:

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

那么,是否可以在模型中使用“请求”方法? 如果是这样,怎么办?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

属性 2024-10-22 01:51:08

不可以,因为该请求仅在控制器和视图代码中可用。从设计的角度来看,不建议您在模型代码中使用该请求,但是假设您想对 User 的特定实例上的请求执行某些操作,只需为其创建一个方法:

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

然后在您的其他地方应用:

User.has_a_request?(request)

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)
诗酒趁年少 2024-10-22 01:51:08

在方法中使用请求对象并不是一个好的应用程序设计,但如果您确实需要它,您可以这样做:

class User
  def a_method request
  end
end

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

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
柏拉图鍀咏恒 2024-10-22 01:51:08

从控制器中的请求对象中提取相关数据,然后将它们传递到模型 - 通过在其实例上设置属性或将它们作为参数传递给方法调用。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文