MVC Design – Is It Okay to Call a Model Method in a View?

mvcrefactoringruby-on-rails

In the interest of keeping my Controller's skinny, I put a headline method in a Model.

# My Model
class Property
  def headline 
    "#{name} | #{address}"
  end
end

(Then, Property Controller for context…)

# My Controller    
class PropertyController
  def show
    @property = Property.find(params[:id]) 
  end
end

Question: As far as MVC is concerned, is it okay to call that Model method from my View, like so?

# My View
<h1><%= @property.headline %></h1>

Best Answer

In certain MVC variants, the view gets notified of changes in the model via the controller: the view registers as a listener on model-changed notifications, but the view never calls methods of the model (see e.g. the diagram in the wikipedia article).

In another variant, the view queries (calls getter methods of) the model directly to get the data to be displayed. However, the view should only be able to query the model, not to change its contents. To my knowledge, this is the JSP approach: the view (a JSP page) can contain queries that get data from the model to be rendered with the rest of the page.

As far as I understand, your example follows the second approach and it is therefore OK since the view is only querying the model via @property.headline.

Related Topic