简体   繁体   English

Rails在Controller中建模方法可用性

[英]Rails model methods availability in Controller

I have a method in my model which should detect the User Agent. 我的模型中有一个方法可以检测用户代理。 How can I make it available to all my controller methods? 如何使其可用于我的所有控制器方法?

Model: 模型:

  def is_iphone_request?
       if request.user_agent =~ /iPhone/
       return true
     end
  end

Controller (throws an error): 控制器(引发错误):

def index
  @user_agent = is_iphone_request?
end

How can I achieve this? 我怎样才能做到这一点? Any help is much appreciated. 任何帮助深表感谢。

将方法放在ApplicationController而不是模型中。

I'm not sure why you've put the request user-agent check on the model--it seems like a controller centric behavior. 我不确定你为什么要对模型进行请求用户代理检查 - 这似乎是一种以控制器为中心的行为。 And there is a request attribute IN a controller that you can use. 控制器中有一个可以使用的请求属性。

Though request will not be available in the model (you will get a NameError with the following code), your current problem is that the controller is throwing a NoMethodError because you are missing self. 尽管该request在模型中将不可用(您将获得以下代码的NameError ),但当前的问题是由于缺少self. ,控制器抛出了NoMethodError self. on the method definition. 在方法定义上。 Make it a class method (by adding self. ): 使它成为一个类方法(通过添加self. ):

class MyModel < ActiveRecord::Base
  def self.is_iphone_request?
   if request.user_agent =~ /iPhone/
     return true
   end
end

Then, in your controller, you can use: 然后,在您的控制器中,您可以使用:

MyModel.is_iphone_request?

But like I said, you will get a NameError because request is not available in the model. 但就像我说的那样,你会得到一个NameError因为模型中没有request

Your method is_iphone_request? 你的方法is_iphone_request? should probably live in your ApplicationController (where it can be a regular private method). 应该存在于ApplicationController (它可以是常规的private方法)。 You can also trim it down: 您也可以修剪它:

class ApplicationController < ActionController::Base
  ...
  private
  def is_iphone_request?
    request.user_agent =~ /iPhone/ ? true : false
  end
end

Then, in your controller, you can use: 然后,在您的控制器中,您可以使用:

is_iphone_request?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM