简体   繁体   English

使模型访问Rails中的params哈希的最佳方法是什么?

[英]What is the best way to give a model access to params hash in Rails?

This appears to be a violation of MVC, so I'll explain what I am trying to do: 这似乎违反了MVC,因此我将说明我要执行的操作:

My model makes a call to an API, and the URI of the API depends on the params hash. 我的模型调用了一个API,该API的URI取决于params哈希值。 (The params hash stores the URL of the Rails app). (参数散列存储Rails应用程序的URL)。

I created a module to mix into the model (because the model has nothing to do with the API call), but haven't figured out how to get the params into the module. 我创建了一个模块以混合到模型中(因为该模型与API调用无关),但是还没有弄清楚如何将参数添加到模块中。

If possible, I would like to initialize the module with the params hash, but don't know where to do it. 如果可能的话,我想用params哈希值初始化模块,但是不知道在哪里做。 before_create on the model would work, but that is in the model.rb file which doesn't know about the params. 在模型上的before_create可以使用,但这在不知道参数的model.rb文件中。

Couple ideas, depending on your needs: 几个想法,取决于您的需求:

Pass the parameters to the model with each call, if they change that much. 如果参数发生很大变化,请在每次调用时将其传递给模型。 You could do a class method or instance method - 您可以执行类方法或实例方法-

Model.api_call params[:field]
@model.api_call params[:field]

Save the parameters as class variables in the model: 将参数另存为模型中的类变量:

Model.set_parameters(params)

def self.set_parameters(params)
  @@params = params
end

# access it in methods with @@params

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

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