Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 854
sidney Avatar asked Jun 21 '12 13:06

sidney


People also ask

How do you call a model on a controller?

To call the model method on an object created by the new keyword on user model you have to include user model in your controller file by using the use keyword like use App\Models\UserModel;.

Can we call controller method in model rails?

As the two answers said, you should not be calling controller methods from your models. It is not recommended.


2 Answers

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

like image 140
ben Avatar answered Sep 25 '22 05:09

ben


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

def self.method_name   .. end 

and not

def method_name   ... end 

2.) This can be done using a scope with lambda these are really nice features. Like This in the model add:

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 ProjectPage model so everything is at the place it belongs to!

3.) When you call a Class method in the Controller you need to specifiy the Model like this:

Class.class_method 
like image 20
davidb Avatar answered Sep 22 '22 05:09

davidb