I have some questions regarding how to avoid having to duplicate code
in the controller between certain actions such as “new”, “create”,
“edit”, “update”, etc.
Currently, my “new” and “update” actions both load a couple
collections of reference data used to populate drop-down/select
controls in the view. To avoid duplicating the same code in both
actions, I am defining a before_filter:
class MyController before_filter :find_states, :only => [:new, :edit] before_filter :find_categories, :only => [:new, :edit] ... # action definitions private def find_states @states = State.find(:all, :order => "name") end def find_categories @categories = Category.find(:all, :order => "name") end end
So this is all well and good, the new and edit actions are just fine.
However, my issue is really with the “create” and “update” actions
which are responsible for actually updating the DB. In the case where
the save or update operations fail, these methods will try to render
the “new” or “edit” views. In this case, I need to make sure the
reference data that is required is populated.
I see several solutions to this problem, but none of them particularly
strike me as great solutions, or seem particularly DRY. So I guess I’m
just looking for something a little better/cleaner/DRYer, however you
want to put it.
Anyhow, my current ideas for solutions, none of which I really like,
are as follows:
In the “create” and “update” actions, call the filter methods
prior to rendering the new/edit views (don’t like this, since if
additional reference data is added later, I will have to add/remove
more method calls)
Add additional helper methods that set all of the reference data
for a particular action (i.e. find_ref_data_for_new) (this is better
than option 1, but would still potentially have to modify code in
Add “create” and “update” to the list of actions included in the
before_filter (this would work, but it just doesn’t make sense, since
“create” and “update” are really DB related actions, and only display
data when some DB operation, or validation, fails)
Any help or suggestions would be greatly appreciated.