Forum: Ruby on Rails Accessing model objects directly in the view

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
41faf43c75285adfd4eea7f1140db3bd?d=identicon&s=25 Joe Dzikiewicz (jdzik)
on 2007-07-09 17:01
(Received via mailing list)
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?

F5d61a3c93217e393cfdf7bf5c7ac628?d=identicon&s=25 Michael D. Ivey (Guest)
on 2007-07-09 17:15
(Received via mailing list)
> 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.
413faf211358af7cae68c1f2137de0f8?d=identicon&s=25 Mel Riffe (Guest)
on 2007-07-09 17:23
(Received via mailing list)
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.

This topic is locked and can not be replied to.