Question

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
Was it helpful?

Solution

You should save the model in controller otherwise you will endup making too many sql quires.

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top