Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good practice -- Redirection in models? -- Rails 3.1

I have a Search model and controller. The business logic is that if the user's keyword exact matches a product's model number, redirect them to the product page.

In this situation, should I just do the redirection from inside the model (where most of the logic resides already)?

Or should I return a flag or something to the controller so I can handle the redirect?

like image 735
Jacob Avatar asked Nov 16 '11 12:11

Jacob


2 Answers

THe model object cannot ans shall never do a redirect. The application logic is the duty of the controller, so the controller should ask the model object (as result of a request) if the product matches a model number, and then the controller does the redirect. The model object should not know anything about controller or views. This is part of the "Model-View-Controller concept" this is implemented by Rails.

Rails implements the model as the ActiveRecord pattern, so it is ok that the model object is responsible for the database, and that includes the search on the database. See the many options you have in the Rails Guides for ActiveRecord Queries to see what falls in the responsibility of the model objects.

like image 140
mliebelt Avatar answered Oct 18 '22 10:10

mliebelt


Always remember MVC pattern: MVC in Rails

Model must not take care of redirection or some other stuff that related to controller. Let redirection be in controller.

like image 21
bor1s Avatar answered Oct 18 '22 09:10

bor1s