【问题标题】:How to handle many forms on one page?如何在一页上处理多个表单?
【发布时间】:2009-10-28 19:26:19
【问题描述】:

如果我有一个包含多种形式的现有记录的页面:

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

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

selection.errors.on(:user_id)

其中一种形式?

【问题讨论】:

    标签: ruby-on-rails forms


    【解决方案1】:

    通常你会想要使用 error_msg_for 帮助器。

    = 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
    

    【讨论】:

    • 我收到此错误:@#<0x0000010276a000>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-30
    相关资源
    最近更新 更多