cluster1
cluster1

Reputation: 5694

Confused about Rails MVC: Why can the view invoke model-methods?

I got this Model-method:

class Post < ApplicationRecord
    def details
        "This post was created on #{created_at.strftime("%d %M %Y")}"
    end
end

In the controller: I create a variable which has the return-value of the method.

def show
    @test = @post.details
end

In the view I display the value of the variable 'test' (first paragraph).

<p>
  <%= @test %>
</p>

<p>
  <%= @post.details %>
</p>

But moreover: I can invoke the model-method directly from the view. Second paragraph ...

That really confuses me, because I thought that wouldn't be possible at all.

I thought that only the controller can invoke the model-methods and that it (the controller) creates the variables, which are then available within the view ... So that the model and view are separated and decoupled.

But they way it is (obviously), the model and view would become merged together anyway.

What sense makes the controller at all, when the view can invoke model-methods itself?

Upvotes: 0

Views: 26

Answers (1)

rmlockerd
rmlockerd

Reputation: 4136

The purpose of the controller is to coordinate the appropriate response given a request or action. Ideally views have no significant business logic in them. The controller coordinates that activity -- things like running queries, loading objects, launching background jobs, etc. -- and then organises the result into data that the view can easily consume for rendering.

However, that doesn't mean they can't (or shouldn't) receive model objects or call methods on them. Models also have a relationship with views. Models themselves should ordinarily be quite light on business logic themselves, with most public methods being simple attribute getters. It's simpler and cleaner in many cases for the controller to simply pass the model instance to the view and let the view extract the attributes it needs for display. The role of the controller in that case is loading the right model, rendering the right view and connecting the two.

For example, suppose you have a User model which the standard sort of name, birth date, whatever data attributes. It that case it is customary for the controller to simply load the correct User object, and in fact Rails orients many of its view helpers to quickly create views around a given model:

<%= form_for @person do |f| %>
  <%= f.label :first_name %>:
  <%= f.text_field :first_name %><br />

  <%= f.label :last_name %>:
  <%= f.text_field :last_name %><br />

  <%= f.submit %>
<% end %>

The controller is absolutely the place for (or at least place to initiate) more sophisticated processing when you need to process data for display. A simple example of that would be sorting an array of Users before rendering the view.

Upvotes: 1

Related Questions