[email protected] wrote:
> When creating a view to display infromation obtained from a model,
> should the view always get this information from the controller, or
> should it get it directly from the model?
Which one is simplest?
I think it's ideal when the controller sets up a single variable, such as
@datagram, and then the view uses only first-level method calls on @datagram:
@datagram.marbles.each do |marble|
<%=h marble.name %>
end
Simplified eRB, of course, but you get the idea. We did not call
@datagram.method.method(42).method.marbles. The model and controller should
have
set any parameters up for @datagram to do its job, such as provide the 42.
(.each is technically a method call, but it's more stable, and it's essentially
a part of Ruby's core mechanics, so we give it a pass. We would not give
.select{} or .inject{} the same pass!)
> For example, say I have Class and Student models, and they are in a
> many to many relationship via the enrolled table. Now my view wants to
> display the students of a given class. Should the controller run the
> query and store it in a variable (say @students) that is passed to the
> view? Or, should the view just access it directly like
>
> <% for enrolled in @class.enrolled_students %>
> <%= enrolled.student.name %>
I can think of no reason to use 'for in' in Ruby. I suspect Matz added it
early,
to imitate languages that must use 'for'...
But your enrolled.student.name (is missing an h, and) has too many dots. I
suspect that would violate something called the "Law of Demeter" if any of
those
dots took a "left-turn" into another high-level module.
Because you will find enrolled delegating to student frequently, your code is
already more dry if enrolled has a def name; student.name; end. That hides a
dot
in the model, which is the ultimate goal of refactoring - dense models,
aggressive but sparse controller actions, and thick views with minimal Ruby
method calls.
The controller is like the Government. Paraphrasing Abe Lincoln, it should only
do what the model and view can't do for themselves.
> I like the second way because it does not require me to put any code
> in the controller. I just feel like this is coupling the view and to
> the model and I can't tell if that is a bad thing in an MVC framework?
> I feel like it is.
Coupling the view to the model is part of MVC. Look up one of the diagrams - I
think there's an arrow from the V to M...
--
Phlip
http://flea.sourceforge.net/resume.html
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---