Call Model Method

Hello Everyone

any one know how to call model method in controller ?

I have one method that is in model and want to call from another
controller

please help me

thanks

Is it a class method or an instance method? Meaning do you call it from
an instance of that model:

@model.some_method

Or do you call it on the model itself:

Model.some_method?

If it’s an instance method, you just need to have an instance in the
controller action:

def index
@instance = Model.find(params[:id])
@instance.some_method
end

If you’re dealing with a class method you would do this:

def index
Model.some_method
end

Note: swap out “Model” for the actual name of the model (User, BlogPost,
etc.)

Hope this helps. Post if you have any other questions.

– Josh
http://iammrjoshua.com

Cyrus D. wrote:

Hello Everyone

any one know how to call model method in controller ?

I have one method that is in model and want to call from another
controller

please help me

thanks

Model.method

Controllers and models are not related so you can do this from any
controller

On 04/02/2009, at 16:36, Cyrus D. [email protected]

If you make sure that method is defined with “self”, you can call it
from the controllers. For example,

#A Method that can be called from a controller.
def self.my_hello_string
“Hello!”
end

Now you can say Model.my_hello_string from a controller, and it will
return what you expect, instead of complaining that the method isn’t
defined.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs