Accessing model objects directly in the view

Is there any general guidelines for accessing model objects directly
in the view?

It seems like it would be a potential problem - that it would be
better to keep model objects out of the view entirely. Instead, the
controller should extract whatever data is needed from the model and
put it into temporary objects, thus protecting the views from any
changes in the models and keeping them from causing any problems by
inadvertently calling things in the model.

On the other hand, this in effect creates a new structure just for
passing data from controller to view, when the models already
structure the data in question. That seems like duplicate effort, and
not at all in the spirit of Rails.

Is there any common thought on this?


Is there any general guidelines for accessing model objects directly
in the view?

The best way to answer “general guidelines” type of questions is to
look at the source.

In this case, look at what the scaffold_resource generator does for you.

You’ll see lots of @mymodel and @mymodels throughout the views.

Using models, and collections of models, in the view is not only a
Good Thing, but the alternative seems like madness to me.

The only time I use an abstraction layer is when allowing user-edited
templates. For that kind of thing, look into Liquid and the way it
wraps models in drops.

For general development, though, use your models. That’s why they
are there.

Note: if you find yourself doing things like <% @mymodel.destroy %>
that is Bad. But <%= %> is good.

Generally speaking, MVC states a View can ask a Model for information to
display. However a View cannot ask a Model to perform Business-oriented
operations. The Controller will retrieve requested Models for a View
via a View submission ask a Model to perform business operations. The
Controller should not affect the display of a Model short of providing
it to
the View.