0

我是 ROR 编程的新手,我的问题可能看起来是新手!

我有一个 Rails 项目。我需要在不刷新页面的情况下保存订阅者数据!

在代码块“app/views/users/new.html.haml”的最后一行中,我需要将 form.button 更改为一个 ajax 按钮。我在项目中包含了 jQuery。我应该如何编码?回答时请考虑我是初学者!

提前谢谢你!(-_^)


这是路线:

users_new GET  /users/new(.:format)    users#new
users     GET  /users/index(.:format)  users#index
create    POST /users/create(.:format) users#create

这是我的 app/views/users/new.html.haml:

.form1
  %h1
    Subscriber
  =form_for @user, :url => :create do |form|
    - unless @user.errors.empty?
      - @user.errors.full_messages.each do |message|
        .alert.alert-danger
          %ul
            - @user.errors.full_messages.each do |message|
              %li= message
    %div
      .row.form-group
        .col-lg-3
          %label
            Email:
          =form.text_field :email, :class => 'form-control'
      .row.form-group
        .col-lg-3
          %label
            Name:
          =form.text_field :name, :class => 'form-control'
      .row.form-group
        .col-lg-3
          %label
            Phone Number:
          =form.text_field :phone_number, :class => 'form-control'
      .row.form-group
        .col-lg-3
          %label
            Address:
          =form.text_field :address, :class => 'form-control'
      %div=form.button 'Save', :class => 'btn btn-primary'

这是 app/controllers/users_controller.rb:

 class UsersController < ApplicationController

   def index
   end

   def new
     @user = User.new
   end

   def create
     @user = User.new params[:user]
     @user.save
     redirect_to users_new_path
   end

 end
4

1 回答 1

1

要使表单真正成为 ajax 表单,您只需将 remote 选项设置为 true,这将使用 ajax 自动发送表单:

=form_for @user, :url => :create, :remote => true do |form|

您还需要对它做出一些回应。这是关于该主题的精彩 Railscast: http ://railscasts.com/episodes/136-jquery-ajax-revised

于 2013-11-02T09:16:21.647 回答