Blackninja543
Blackninja543

Reputation: 3709

Best Practice: Where to place a function which is called from view

I am new to Ruby on Rails and the whole MVC style of doing things. This question isn't so much technical as it is conceptual. Say I have some function myFunction that I wish to have a user execute from the View by pushing a button. Should I have this function in thew Model, or the controller?

Upvotes: 1

Views: 60

Answers (3)

AnkitG
AnkitG

Reputation: 6568

Controller's are just expected to have the Input and Output which is the request parameters and the response/redirect. So according to you if a user clicks a button and myFunction should come into picture. Put the call to myFunction inside the view helper and the function myFunction inside the model. So your View is also clean from code and the Skinny controller and Fat models come into picture

Upvotes: 0

mikej
mikej

Reputation: 66263

If the function relates clearly to a particular model e.g. "placing an Order", "authenticating a User" then place it on the appropriate model and add a small amount of controller code to create/retrieve the appropriate model and call the method.

If it doesn't obviously belong on one of your models then you may want to create a separate class or module for it, and again add a small amount of controller code.

Do some Googling for "skinny controllers and fat models", this is the approach generally favoured for Rails projects. e.g. see this (old, but still useful) post from Jamis Buck, or this more recent post.

Upvotes: 1

Marcin Olichwirowicz
Marcin Olichwirowicz

Reputation: 890

It should goes to controller's method which is using models to do some business logic (not necessary connected with persistance). Probably, you should also read about RESTful apps and routing (there is a lot of guides about it).

Upvotes: 0

Related Questions