Reputation: 13568
I want to do some things with a model. I am following the fat model, skinny controller approach.
Should I save the model in the model functions or in the controller? And why?
For instance:
# in package_controller.rb
def do_stuff
package.do_something
package.do_another_thing
package.save
end
# in package.rb
def do_something
self.foo = "bar"
end
def do_another_thing
self.apple = "banana"
end
vs
# in package_controller.rb
def do_stuff
package.do_something
package.do_another_thing
end
# in package.rb
def do_something
self.foo = "bar"
self.save
end
def do_another_thing
self.apple = "banana"
self.save
end
Upvotes: 1
Views: 1070
Reputation: 13
The reason that you would normally see package.save in the controller is that you may have different render/redirect options if the package.save fails or succeeds. For example, if the save fails, you may want to redirect the user back to allow any package validation errors to be corrected. If the package.save succeeds, you may want to redirect them to another route/action.
Upvotes: 0
Reputation: 27779
It just depends whether you want the flexibility to do something without saving. If you're only ever going to do something AND save, you might was well do both in the same method. But if do_something
does something that's worthwhile without saving, and you might want to do that thing without saving, it makes sense to keep those operations separate.
Upvotes: 2
Reputation: 8122
You should save the model in controller otherwise you will endup making too many sql quires.
Upvotes: 2