views:

126

answers:

2

I'm wondering how many data access should I do in a View when using a MVC framework. For instance: In my application there is a page that shows a list of all my favorite artists and, for each artist, a list of all songs of that artist. The question is: Should I pass only the artist list to the View, or should I pass also all the data (artist + songs)?

Ps: I'm using Ruby On Rails and ActiveRecord.

+2  A: 

Assuming the model class for Artist has a means to provide a collection of Songs I see no reason to require the controller to explictly pass both to the view.

AnthonyWJones
+3  A: 

Don't pull db data in views - that's the controller's job. In your views, you should only reference data loaded by your controller method.

In your case, that means creating the artist list, using :include so the songs are pre-loaded.

# In your controller
@artists = Artist.find(:all, :include => :songs)

EDIT In response to method's comment, there are two issues with pulling data from views:

  • Separation of concerns. This is what I was talking about when I said you "should" only pull data in the controller - in MVC the controller handles data access and, in theory, the views don't contain logic. It's certainly easier to put some data retrieval in your views at times, but it gets ugly pretty quick.
  • Efficiency, either in number of queries or query result size, which I think is what method was talking about. If you're loading enough data in a single page that this becomes an issue, I wonder if that doesn't suggest some refactoring (or at least pagination).
Sarah Mei
Does this really matter? Why not just <%= artist.songs %>, especially if there's conditional logic that means the songs won't be requested at all. I may not understand the issues involved, though. I thought AR did lazy loading, and that retrieving fewer records is more efficient than fewer queries.
method