Forum: Ruby on Rails Call Model Method

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Cyrus D. (Guest)
on 2009-02-04 08:36
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
Joshua A. (Guest)
on 2009-02-04 08:51
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
Ryan B. (Guest)
on 2009-02-04 10:32
(Received via mailing list)
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. <removed_email_address@domain.invalid>
Endikos (Guest)
on 2009-03-19 19:26
(Received via mailing list)
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 topic is locked and can not be replied to.