Einar
Einar

Reputation: 3317

Rails RESTful controllers vs. view specific controllers

This design question needs a bit of context, so please bear with me.

I currently have three models that go something like this:

class MyItem < ActiveRecordBase
    has_many :my_list_items
    ...

class MyList < ActiveRecordBase
    has_many :my_list_items
    has_many :my_items, :through => :my_list_items
    ...

 class MyListItem < ActiveRecordBase
     belongs_to :my_item
     belongs_to :my_list
     has_many :my_list_item_properties

 class MyListItemProperty < ActiveRecordBase
     belongs_to :my_list_item

As you can see, the MyListItem model is more than a simple join table, it has other properties as well.

There are two main views in the application. One displays all MyItems regardless of which MyList it belongs to, and provides standard CRUD operations for these. The other view displays a MyList, with data from all its MyListItems and the associated MyItem of each. This view allows inline editing to existing MyItem objects (that are associated with the list via MyListItem), and inline forms to create new MyItem objects and associated MyListItem. These inline actions rely largely on partials and RJS.

Now I have two options:

Which method do you prefer and why?

Upvotes: 3

Views: 405

Answers (2)

njorden
njorden

Reputation: 2606

I often have this debate with myself also and I think I usually favor option #1. As a best practice we're usually striving for skinny controllers and looking for ways of factoring initialization/creation logic into the Model. In a perfect world, most of the logic in the action would be the view specific rendering/redirect logic that you'd be branching on for option #2.

I also feel the requirements tend to diverge over time for different views: "We'd like to show a different flash message on this page". Which would be just more branching for option #2.

After factoring any initialization logic that's reasonable to the model and maybe using a common before_filter in the controllers, option #1 would likely feel pretty clean & DRY.

Upvotes: 3

Ben Lee
Ben Lee

Reputation: 53309

My initial inclination here would be your first suggested option, but with a lib module (that both controllers include) to DRY up any duplicated code or logic surrounding MyItems (of course, as much as possible should by DRYed up in the MyItem model first). This keeps the code both simple and maintainable. When you're dealing with complicated AJAX setups like this, the benefits of code logic simplicity outweigh the benefits of a a strictly RESTful approach.

Upvotes: 2

Related Questions