Pensieri di un lunatico minore

30 March 2006 Ruby

MVC in Ruby on Rails

The Model View Controller pattern is old. It dates back to the mid/late 1970s and the origins of Smalltalk. As a pattern for GUIs it works, but has all sorts of problems, however it works reasonably well for web-based applications. This, I think, is why DHH adopted it for RoR. But here’s the thing: the coupling is not evenly distributed between the layers, and scaffolding will lie to you something fierce—leading you down a path with good intentions and ending up in a morass of code.

Now, I’m not talking about situations where you’re using scaffolding to deal with trivial examples. I’m speaking of situations where you have complex applications—not just CRUD—that have to deal with the intertwined data in complex ways. If you’ve not come from the MVC world before, and don’t truly grok it before you start, you might think this is what it looks like:

One controller per model. I’m not saying this isn’t the case sometimes, but it might lead some people down the wrong path. Once you begin to undertake non-trivial Rails applications, you need to understand that your MVC architecture starts to look like this:

Note that while views and controllers are still bound together1 in what I call “near coupling,” the models are not. They’re totally separate. For me, this is critical to understand. Until you decouple the model and controller ideas more fully, you are stuck with odd little baroque creations that have all sorts of bleed-through. This is bad. It’s not how Rails, I think, was intended to be.

This means if you have an Account model, you don’t have to have an AccountController. You might have a MembershipController that talks to Accounts, Preferences, Subscriptions and half-a-dozen other things. Ta’da.

So, use scaffolding to “play” with the system. Use some of the tools to get you up and running quick, but understand their limits. You’ll need to replace lots of them. I often find it’s just easier to whip out the Controllers from scratch without any effort and let them deal with the Models that they need to serve the appropriate Views.

1 Personally, I’ve yet to find any love for Components, but that could certainly change in the future.

This entry was posted at 10:56 pm on 30 March 2006 and is filed under Ruby. You can follow any responses to this entry through the post-specific RSS 2.0 feed.

[...] Nice pictures (and thoughts) at » MVC in Ruby on Rails : Pensieri di un lunatico minore. [...]

“This is bad. It’s not how Rails, I think, was intended to be.”

Given the number of times I paste this link into our IRC channel, figured I should clear this up. You’re completely right, 1-1 mapping between controllers and models is not what we intended.

Responses are currently closed, but you can trackback from your own site.