您可以使用 AJAX 请求来完成此操作form_for帮助者与:remote option.
概括
- Set
:remote
选项true
为您coupons
表单提交 AJAX 请求。
- 创建控制器操作来处理来自表单的 AJAX 请求。
- 使用 JavaScript 响应控制器操作来更新您的
orders
表格(您认为的另一种表格)以及新的价格信息等。
使用 `:remote` 的 AJAX 请求
这是一些代表您的示例代码coupon
form :
<%= form_for @coupon, method: :post, url: check_coupon_code_path, remote: true do |f| %>
<%= f.text_field :coupon_code, :placeholder => "Enter your coupon" %>
<%= f.submit "Submit Coupon Code" %>
<% end %>
请注意以下事项:
- The
:remote
选项为form_for
标签设置为true
.
- The
:url
选项是您的控制器操作的路径CouponsController
。因为:remote
选项设置为true
,请求将发布到此:url
选项作为 AJAX 请求。
- In this code example, it's assuming it has a route defined like this in the
routes.rb
file to handle the AJAX request for checking the coupon code:
post 'check_coupon_code' => 'coupons#check_coupon_code'
- 注:在
forms_for
帮手,那个:url
选项附加_path
到中定义的前缀routes.rb
file.
- 附注:使用命令
rake routes
查看可用路线及其各自的控制器操作目标。
在控制器中处理 AJAX 请求
In your CouponsController
,定义动作check_coupon_code
处理上面的 AJAX 请求form_for
:
def check_coupon_code
# logic to check for coupon code here
respond_to do |format|
if # coupon code is valid
format.js {}
else
# some error here
end
end
end
注意format.js
in the respond_to
动作的块。这允许控制器使用 JavaScript 响应 AJAX 请求来更新您的orders
形式在你看来。你必须定义一个相应的app/views/coupons/check_coupon_code.js.erb
查看生成将在客户端发送和执行的实际 JavaScript 代码的文件(或将 JavaScript 文件命名为check_coupon_code.js.coffee
如果您使用的是 CoffeeScript)。
使用 JavaScript 更新
你的 JavaScriptcheck_coupon_code.js.erb
文件将更新您的价格order
form.
WARNING:即使您使用 JavaScript 在客户端(即浏览器)更改订单价格,在后端(即在您的控制器中)再次验证实际价格也至关重要,以防某些恶意用户试图操纵浏览器的请求等
你可以查看官方的 RailsGuide 来了解另一个example.