Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

ruby on rails - Call a model method in a Controller

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.

question from:https://stackoverflow.com/questions/11139605/call-a-model-method-in-a-controller

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...