Ruby-on-rails 在控制器中调用模型方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11139605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call a model method in a Controller
提问by sidney
I'm have some difficulties here, I am unable to successfully call a method which belongs to a ProjectPagemodelin the ProjectPagecontroller.
我有一些困难,在这里,我无法成功地调用它属于一种方法ProjectPage模型的ProjectPage控制器。
I have in my ProjectPagecontroller:
我的ProjectPage控制器中有:
def index
@searches = Project.published.financed
@project_pages = form_search(params)
end
And in my ProjectPagemodel:
在我的ProjectPage模型中:
def form_search(searches)
searches = searches.where('amount > ?', params[:price_min]) if check_params(params[:price_min])
@project_pages = ProjectPage.where(:project_id => searches.pluck(:'projects.id'))
end
However, I am unable to successfully call the form_searchmethod.
但是,我无法成功调用该form_search方法。
回答by ben
To complete davidb's answer, two things you're doing wrong are:
要完成 davidb 的回答,您做错的两件事是:
1) you're calling a model's function from a controller, when the model function is only defined in the model itself. So you do need to call
1)当模型函数仅在模型本身中定义时,您正在从控制器调用模型的函数。所以你需要打电话
Project.form_search
and define the function with
并定义函数
def self.form_search
2) you're calling params from the model. In the MVC architecture, the model doesn't know anything about the request, so params is not defined there. Instead, you'll need to pass the variable to your function like you're already doing...
2)您正在从模型中调用参数。在 MVC 架构中,模型对请求一无所知,因此那里没有定义 params。相反,您需要将变量传递给您的函数,就像您已经在做的那样......
回答by davidb
Three thing:
三件事:
1.) When you want to create a class wide method thats not limited to an object of the class you need to define it like
1.) 当您想创建一个类范围的方法时,该方法不仅限于类的对象,您需要像这样定义它
def self.method_name
..
end
and not
并不是
def method_name
...
end
2.) This can be done using a scopewith lambdathese are really nice features. Like This in the model add:
2)这可以使用来完成scope与lambda这些真的很不错的功能。像这样在模型中添加:
scope :form_search, lambda{|q| where("amount > ?", q) }
Will enable you to call
将使您能够打电话
Project.form_search(params[:price_min])
The secound step would be to add a scope to the ProjectPagemodel so everything is at the place it belongs to!
第二步是为ProjectPage模型添加一个范围,这样一切都在它所属的地方!
3.) When you call a Class method in the Controller you need to specifiy the Model like this:
3.) 当您在控制器中调用类方法时,您需要像这样指定模型:
Class.class_method
回答by Kashiftufail
Declare like this in model
在模型中这样声明
def self.form_search(searches)
searches = searches.where('amount > ?', params[:price_min]) if check_params(params[:price_min])
@project_pages = ProjectPage.where(:project_id => searches.pluck(:'projects.id'))
end
and call from controller
并从控制器调用
@project_pages = ProjectPage.form_search(params)

