我的表格效果很好。这是我的部分内容:
<%= form_for @reservation, url: {controller: 'reservations', action: 'create'} do |f| %>
<div class="row">
<div class="col-sm-8 col-sm-offset-1">
<div class="form-group">
<%= f.text_field :name, class: 'form-control', id: 'name', placeholder: 'Party Name', required: true %>
</div>
<div class="form-group">
<div class="col-sm-4">
Party Size:
</div>
<div class="col-sm-6">
1 <%= f.radio_button :party_size, '1'%>
2 <%= f.radio_button :party_size, '2'%>
</div>
</div>
<div class="col-sm-4 col-sm-offset-8">
<div class="form-group">
<%= f.submit 'submit', class: 'btn default-btn btn-block' %>
</div>
</div>
</div>
</div>
以下是控制器操作create
:
def create
@reservation = Reservation.new(reservation_params)
@reservation.customer_id = session[:customer_id]
if @reservation.save
redirect_to :back
else
render 'reservations/new'
end
end
我想render 'reservations/confirmation'
代替当前的部分reservations/form
。我知道我需要将remote: true,
添加到form_for
标记中,但我会被卡在那里。什么&amp;我需要在JS中编写什么才能使这个提交函数与AJAX一起工作?我需要在create
操作中添加什么内容?
答案 0 :(得分:1)
您需要使用$.post()
通过JQuery提交它,并且您还必须使用respond_to
来回复JavaScript提交和正常的HTML提交(如果某人禁用了JavaScript)。
http://guides.rubyonrails.org/working_with_javascript_in_rails.html#server-side-concerns
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.js {}
format.json { render json: @user, status: :created, location: @user }
else
format.html { render action: "new" }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end