[LRUG] Embarrassing Newbie question

dblack at rubypal.com dblack at rubypal.com
Mon Aug 13 11:45:41 PDT 2007


Hi --

On Mon, 13 Aug 2007, Craig Webster wrote:

> On 13 Aug 2007, at 19:15, Ben Rooney wrote:
>> Is there a 1:1 relationship between controllers and models? ie does
>> every model have an associated controller, or can one controller
>> control more than one model.
>
> There doesn't need to be a controller for each model or a model for
> each controller. One controller can manage multiple models, but it'll
> add complexity to the controller and I'd suggest it should be
> avoided. One to one groups responsibilities nicely.
>
>> I have an app I would like to build in RoR (quite heavy on Ajax and I
>> don't fancy doing AJAX in PHP ...). It has about 20 or so models -
>> the bulk of the work is going to be CRUD but there will be some cases
>> of more complexity. So for example if I had a User class, and an
>> organisation class which are going to be predominantly CRUD ops,
>> could one controller do that, or do I need one for each?
>
> I'd use one controller for each resource I wanted to manage with the
> application. If you wanted to work with the User model, I'd have a
> UsersController. If you wanted to manipulate an Organisation, that's
> an OrganisationsController.
>
> The one model too one controller idea works well when playing with
> REST[1] and can help structure your application in a maintainable,
> easily understood manner. It's possible to fit most scenarios into
> the constraints provided by a RESTful architecture, but it can be a
> bit strange at first. What complexity beyond CRUD operations do you
> see in your application?

I think, though, that sometimes there's too much emphasis placed on a
resource consisting of a controller/model stack.  The example that
always comes to mind is a shopping cart.  When I was working on my
(non-RESTful) sample application for "Ruby for Rails", I kept thinking
I should have a shopping cart model... but eventually I concluded that
the "shopping cart" is really just a view of a bunch of order objects.
If I were doing the same thing in a RESTful/resource-routing way, I
would probably conceive of the shopping cart as a resource, even
though there's no associated model.

This is one reason that I have qualms about the resource scaffolding:
it creates both a model and a controller.  They definitely go together
a lot of the time, but I think they're too tightly coupled by the
scaffolding.

Anyway, everybody come to RailsConf Europe and we can ask Roy Fielding
about it! :-)


David

-- 
* Books:
   RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242)
   RUBY FOR RAILS (http://www.manning.com/black)
* Ruby/Rails training
     & consulting:  Ruby Power and Light, LLC (http://www.rubypal.com)



More information about the Chat mailing list