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.
7694e527192e45b73b95f2ca41034463?d=identicon&s=25 Cyrus Dev (cyrusdev)
on 2009-02-04 07: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
36aef9956c6082f69622dd67e8da376f?d=identicon&s=25 Joshua Abbott (joshnabbott)
on 2009-02-04 07: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 Dev 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
9a2a53db8e9b4476038c94a64b32833f?d=identicon&s=25 Ryan Bigg (ryan-bigg)
on 2009-02-04 09: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 Dev <rails-mailing-list@andreas-s.net>
A9ed2115dc6e6dca0882ada62307a8dd?d=identicon&s=25 Endikos (Guest)
on 2009-03-19 18: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.