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

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

问题描述

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

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

我的 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 方法.

However, I am unable to successfully call the form_search method.

推荐答案

为了完成 davidb 的回答,你做错的两件事是:

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

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

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

并用

def self.form_search

2) 您正在从模型中调用 params.在 MVC 架构中,模型对请求一无所知,因此那里没有定义 params.相反,您需要将变量传递给您的函数,就像您已经在做的那样......

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

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

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