Rails 3.1提交表单而不刷新

时间:2012-04-10 16:54:30

标签: jquery ruby-on-rails ruby-on-rails-3

我的orders/_form.html.erb上有一个表单,我想提交并保存在一个名为Categories

的表中
<%= simple_form_for(@category) do |f| %>

  <%= f.error_notification %>

  <div class="inputs">

    <%= f.input :name, 

:label => false, 

:input_html => { :class => 'text', 

:style => 'float:left; width:250px' }, 

:placeholder => "Type of item / name of expense",


%>



   <%= f.hidden_field :user_id, 

:value => current_user.id %>


   <%= f.button :submit, 

:value => 'Add Category', 

:class => 'small grey',

:style => 'margin:5px 0 0 10px' %>


  </div>



<% end %>

在我的categories_controller.rb中,我有这个代码来创建类别:

# POST /categories

  # POST /categories.json

  def create

    @category = current_user.categories.build(params[:category])



    respond_to do |format|

      if @category.save

        format.html { redirect_to new_order_path }

        format.json { render json: new_order_path, status: :created, location: @category }

      else

        format.html { render action: "new" }

        format.json { render json: @category.errors, status: :unprocessable_entity }

      end

    end

  end

首先,我如何制作它,以便在您提交表单时,它不会刷新页面?然后我希望Categories下拉列表http://d.pr/gUwz也有新的条目(我假设使用JQ)。知道怎么让我开始这个吗?

3 个答案:

答案 0 :(得分:2)

使用Rails 3.x,您必须使用表单

:remote => true

前:

<%= form_for @comment, :remote => true, :html => { :'data-type' => 'html', :id => 
 <form code>
<% end %>

并确保包含jquery js文件

欢呼声

答案 1 :(得分:1)

您可以使用以下命令在表单标记中发送ajax请求:

  

:remote =&gt;真

查看有关for_for方法的文档:FormHelper#form_for-instance_method

由于JQuery默认为rails 3.0,因此你应该没有问题。

答案 2 :(得分:0)

需要使用:remote =&gt;如果在表单标记中为true,则会像使用ajax请求一样提交表单,并且表单将在没有刷新页面的情况下提交。

相关问题