开发者

How to handle many forms on one page?

If I have a single page with many forms of existing records:

index.html.haml

- for selection in @selections
  - form_for selection, :method => :p开发者_高级运维ut do |form|
    = form.collection_select :user_id, @current_account.users, :id, :full_name

and then this for submits to and update action:

selections_controller.rb

def update
  selection = Selection.find(params[:id])
  if selection.update_attributes(params[:selection])
    flash[:notice] = "Save!"
    redirect_to selections_path
  else
    flash[:errors] = "Errors"
    render :index
  end
end

How do I handle error messages if I have these multiple forms on the same page. i.e if I want to use:

selection.errors.on(:user_id)

for one of the forms?


Usually you would want to use the error_msg_for helper.

= error_messages_for object

However in you case because you're rendering multiple forms based on the update of a signle one you have a bit more work to do.

First your update action should repopulate @selections and make the selection that failed to update available to the view as an instance variable.

def update
  @selection = Selection.find(params[:id])
  if @selection.update_attributes(params[:selection])
    flash[:notice] = "Save!"
    redirect_to selections_path
  else
    @selections = Selection.find ....
    flash[:errors] = "Errors"
    render :index
  end
end

Next filter this information into your forms.

index.html.erb

- for selection in @selections
  - form_for selection, :method => :put do |form|
    = error_messages_for form.object if form.object.id = @selection.id
    = form.collection_select :user_id, @current_account.users, :id, :full_name
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜