在Controller中调用模型方法 [英] Call a model method in a Controller

查看:97
本文介绍了在Controller中调用模型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里遇到了一些困难,我无法在ProjectPage controller 中成功调用属于ProjectPage model 的方法.

我在ProjectPage控制器中:

def index
  @searches = Project.published.financed     
  @project_pages = form_search(params)
end

在我的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

但是,我无法成功调用form_search 方法.

解决方案

要完成davidb的回答,您做错了两件事:

1)当模型函数仅在模型本身中定义时,您正在从控制器调用模型的函数.因此,您确实需要致电

Project.form_search

并使用

定义函数

def self.form_search

2)您正在从模型中调用参数.在MVC体系结构中,该模型对请求一无所知,因此未在其中定义参数.相反,您需要像已经在做的那样将变量传递给函数...

I'm have some difficulties here, I am unable to successfully call a method which belongs to a ProjectPage model in the ProjectPage controller.

I have in my ProjectPage controller:

def index
  @searches = Project.published.financed     
  @project_pages = form_search(params)
end

And in my ProjectPage model:

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_search method.

解决方案

To complete davidb's answer, two things you're doing wrong are:

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

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...

这篇关于在Controller中调用模型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆