Thanks as well Rob. I like how you guys gave basically the same response at the exact same time. It really shows a lot of uniformity in the community. I was honestly expecting to get a lot of flame back about 'do whatever is best' or something to that effect.
On Apr 19, 5:37 pm, Rob Biedenharn <[email protected]> wrote: > On Apr 19, 2009, at 4:16 PM, [email protected] wrote: > > > > > > > Hi > > > 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? > > > 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 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. > > > Thanks in advance > > Well, except that you may find an iterator better: > > <% @class.enrolled_students.each do |enrolled| %> > <%= enrolled.student_name %> > <% end %> > > In you controller, you probably want to tell ActiveRecord that you'll > be using enrolled_students, but this is just for performance. It will > work in the view as is. > > @class = Class.find(params[;id], :include => :enrolled_students) > > and note that I've subtly suggested that you don't chain the method > calls in the view (ask Google or Wikipedia about the "Law of Demeter") > > class EnrolledStudent > def student_name > self.student ? self.student.name : "anonymous" > end > end > > This lets you avoid NoMethodError exceptions if (when!) > enrolled.student is nil > > -Rob > > Rob Biedenharn http://agileconsultingllc.com > [email protected] --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---

