M. Cypher
M. Cypher

Reputation: 7066

Dynamic translations for model attributes in model or helper?

Let's say I have a Partner model which represents an affiliate partner in an ad network. Each partner is associated with a commission which can be fixed (absolute currency) or variable (percentage). The partners table models this with columns commission_type, commission_fixed and commission_variable. This is a simplification, there are actually 7 commission types, so single-table inheritance or multiple models would require lots of extra code.

In my view, I want to display the commission, like this:

<div class="partner_commission"><%= partner.commission %></div>

(using model method)

or

<div class="partner_commission"><%= commission(partner) %></div>

(using helper method)

Now, one important aspect to note is that the entire application is multilingual, so every string in the view has to be translated with the I18n.translate / I18n.t helper. The translation contains more than just number / currency format, so custom translations for the commission string are needed (never mind why).

The method looks like this (simplified model version):

def commission
  case self.commission_type
  when 'commission_fixed'
    t(:commission_fixed, :value => self.commission_fixed)
  when 'commission_variable'
    t(:commission_variable, :value => self.commission_variable)
  end
end

The question is: Where should I implement the commission method to be in compliance with MVC philosophy, best practices, etc.?

The reason for putting it in the helper would be that it only concerns the presentation of the commission data in the view, not the data itself. On the other hand, a helper method has to be implemented which only concerns a single model, but is used across many views, which feels wrong.

The reason for putting it in the model would be that the commission string can be seen as a derived attribute and hence should be defined in the model. On the other hand, I have to manually include the i18n view helpers to use I18n.translate in the model, which feels strange.

What do you think?

Upvotes: 0

Views: 548

Answers (1)

Max
Max

Reputation: 15985

I would say it should go in the model. Models are supposed to control your data, and that is exactly what you want your commission method to be doing. It is perfectly OK in MVC to use model methods to combine/modify data in order to return it in a nice form.

Upvotes: 0

Related Questions