如何在一个页面上处理多个表单?

问题描述:

如果我有与现有记录多种形式单页:如何在一个页面上处理多个表单?

index.html.haml

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

,然后这对提交给和更新动作:

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 

我该如何处理如果我在同一页面上有这些多个表单,dle错误消息。 即,如果我想使用:

selection.errors.on(:user_id) 

为表单之一?

通常你会想使用error_msg_for helper。

= error_messages_for object 

然而,在你的情况,因为你正在呈现基于一个劲儿地之一的更新多种形式你有一点更多的工作要做。

首先,您的更新操作应重新填充@selections,并将无法更新的选择作为实例变量提供给视图。

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 

接下来将此信息过滤到您的表单中。

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

我收到此错误:@#”不允许作为实例变量名 – Cameron 2009-10-28 21:42:37

+0

没有错误对应哪一行。 – EmFi 2009-10-28 21:52:27

+0

我想我通过使用error_messages_for @selection来修复它 – Cameron 2009-10-28 21:56:00