December 07, 2018

When should I use helper a method vs a model method?

Ademar / December 07, 2018

When should you use a helper method vs a model method?

IMHO, you have to read the entire codebase in order to decide whether you put the method on a model or a helper.

Here's an example on one of our project, the Listing model has these new methods:

class Listing < ApplicationRecord
  def seven_day_pickup_cost
    seven_day_rental_price.to_i + cleaning_fee

  def seven_day_post_cost
    seven_day_rental_price.to_i + delivery_fee + cleaning_fee

  def fourteen_day_pickup_cost
    fourteen_day_rental_price.to_i + cleaning_fee
  def fourteen_day_post_cost
    fourteen_day_rental_price.to_i + delivery_fee + cleaning_fee

I read through the entire Listing class, these methods where not used. Since it involved costs, you are likely to assume that these methods is also involved in a business logic that changes the the database, however, these methods where not used also.These methods where only used in the view.

The question is, should these method be in the model or in the helper

The general answer is:

  • helper methods - are used when these methods are used often in views
  • model methods - are used when these methods are often used in models or "business logic" code in the back-end

The more specific answer to this scenario is they belong to the helper method for two reasons.

Reason number one is they are only used on the view. Putting in the model does not add any "readability" value.

Reason number two is putting them on the Listing model, add more "complexity" when your read the entire workflow that involves money related logic, since it has "cost" on the method name, you are likely to assume that they are part of that workflow.