My rails app has a number of forms that use select tags. To date, to populate these selects I've been initialising an ivar(s).
But it is becoming bit of a maintenance issue. It's easy to remember to populate an ivar when you are in a new
or edit
action. It's the create
and update
actions that are more problematic. Those ivars required by the form only need to be populated when there is an validation (or error) issue with the model.
Considering that the ivars are not needed when responding to xml or json requests, I'm questioning is there a better way.
Is this a case where I should be using helpers within my _form partial? To date I've always considered database access within a helper to be a code smell - but now I'm not so sure.
Just in case my post isn't clear:
def create
@user = User.new(params[:user])
# this is what i do now - but is there a better way
unless @user.save
load_form_required_ivars # here I'm unnecessarily
# hitting the db for json/xml requests
end
respond_with(@user)
end