1

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
4

1 回答 1

0

您可以使用attr_accessorattr_accessible来保存您正在填充的下拉列表的这些值。当您在创建中进行验证时,如果存在验证问题,则将它们的值传回。

但是,我没有得到关于 xml 和 json 不同的部分,但这也应该适用。

于 2012-04-18T12:24:13.553 回答