Rails 3 form_for:remote => true不通过AJAX提交

时间:2011-11-25 23:02:13

标签: ajax ruby-on-rails-3 forms ujs

我正在尝试通过AJAX提交表单。我认为这应该是一件简单的事情,但它坚持以常规形式发布......

更新

此表单是否存在于另一种表单中,该表单不是AJAXified或相关的?这会导致问题吗?

我得到的错误

  

LinkWidgetsController中的ArgumentError #create

     

LinkWidgetsController中没有默认布局   [/用户/ victorstan /站点/肖像/应用/视图,   /Users/victorstan/.rvm/gems/ruby-1.9.2-p290@portrait/gems/devise-1.5.1/app/views]

相关代码:

路由

  resources :profiles do
    resource :link_widgets #this handles the form requests for create
    member do
      get 'new_link_widget' #this handles the form requests for new
    end
    resources :pages
  end

控制器

class LinkWidgetsController < ActionController::Base
  before_filter :authenticate_user!
  load_and_authorize_resource

  def create
    @link_widget = LinkWidget.new(params[:link_widget])

    respond_to do |format|
      if @link_widget.save
        format.js { render :js => @link_widget, :status => :created, :layout => !request.xhr? }
      else
        logger.debug @link_widget.errors.inspect
        format.js { render :js => @link_widget.errors, :status => :unprocessable_entity }
      end
    end
  end
end

部分

%hr
= form_for [@profile, @link_widget], :remote => true, :format => :js do |f|  
  .field
    = f.label :provider
    = f.select(:provider, options_for_select(f.object.providers, f.object.provider))
  .field
    = f.label :link
    = f.text_field :link, size: 37, class: 'input-width'
  .field
    = f.label :title
    = f.text_field :title, size: 37, class: 'input-width'
    %div
      %small.form-help-text If you set an optional title, it will show up beside the icon as a link
  .field
    = f.label :order
    = f.text_field :order, size: 2
  - unless f.object.new_record?
    .field
      = f.label :delete
      = f.check_box :_destroy
  = f.hidden_field :profile_id
  .actions
    = f.submit 'Save', class: 'right'
  .clear

1 个答案:

答案 0 :(得分:2)

如果我理解This form exists within another form的含义,您就会嵌套表单标记(如下所示):

<form> <!-- this is a standard form -->
    ...
    <form> <!-- this is the remote/AJAXified form -->
        ...
    </form>
    ...
</form>

HTML规范不允许嵌套表单标记。您应该将内部表单移动到文档中的另一个位置。如果这不可能,您可以尝试在单个表单中使用两个提交按钮,然后根据按下的按钮采取适当的操作(您可以在服务器上执行此操作)。