views:

188

answers:

2

More and more I'm putting all of my code in models and helpers concerning MVC.

However, sometimes I'm not sure where to organize code. Should it go into the model or should it go into a helper. What are the benefits of each. Is one faster or are they the same. I've heard something about all models getting cached so it seems then like that would be a better place to put most of my code.

For example here is a scenario that works in a model or in helper:

 def status
  if self.purchased
   "Purchased"
  elsif self.confirmed
   "Confirmed"
  elsif self.reserved
   "Reserved"
  else
   "Pending"
  end

end

I don't need to save this status as in the database because there are boolean fields for purchased, and confirmed, and reserved. So why put this in a model or why put it into a helper?

So I'm not sure of the best practice or benefits gained on putting code into a model or into helper if it can be in both.

+1  A: 

This is really subjective and I agree, sometimes it is not clear if something belongs in a model or helper.

For example:

# using model
status ? status.nice_name : "Pending" 
# using helper 
nice_name(status) 

The clear advantage here for the helper is that it can handle nil objects gracefully keeping views clean. The disadvantage is that the code is now in a different location away from the model

Performance wise you will not see any significant difference between using helpers and models. It is more likely that DB round trips to pull status objects will be a bottleneck.

Sam Saffron
+3  A: 

Your specific example is including a business rule in the sense that if the instance of the model is both purchased and confirmed then the proper status is "purchased" not "confirmed"

So in your example, I'd definitely put the method in the model since it is coding one of your applications business rules.

A different example:

def status_string
  case status
    when 0: "Purchased"
    when 1: "Confirmed"
    else
      "Pending"
   end
end

In this case, the status_string method could be reasonably defined either in a View Helper or Model--it has nothing to do with any business rules, it is changing the representation of the value. I'd put it in the model since I tend to only put html-related sw into the View Helpers. But depending on your internationalization scheme, a similar method might be better placed in the View Helper.

A good example of a View Helper is an application-wide method to transform date time values into the standard representation for your app. Eg

# application_helper.rb
def date_long_s(d)
  d.strftime("%A, %b *%d, %Y *%I:%M %p")
end
Larry K
+1 for - "I'd definitely put the method in the model since it is coding one of your applications business rules."
Srikanth Venugopalan
another +1 for whatever Whiskey said.
Anurag