Ruby on rails and coupon model

寵の児 提交于 2019-12-01 13:37:48

You can accomplish this with an AJAX request using the form_for helper with the :remote option.

Summary

  1. Set :remote option to true for your coupons form to submit the AJAX request.
  2. Create controller action to handle the AJAX request from the form.
  3. Use JavaScript to respond to the controller action to update your orders form (the other form in your view) with the new price information, etc.

AJAX request using `:remote`

Here's some example code representing your 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 %> 

Notice the following:

  • The :remote option for the form_for tag is set to true.
  • The :url option is the path to your controller action in your CouponsController. Because the :remote option is set to true, the request will be posted to this :url option as an AJAX request.
  • 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'
    • Note: In the forms_for helper, the :url option appends _path to the prefix defined in the routes.rb file.
    • Bonus note: Use the command rake routes to see the available routes and their respective controller action targets.

Handle AJAX request in the Controller

In your CouponsController, define the action check_coupon_code to handle your AJAX request from the above 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

Notice the format.js in the respond_to block of the action. This allows the controller to respond to the AJAX request with JavaScript to update your orders form in your view. You'll have to define a corresponding app/views/coupons/check_coupon_code.js.erb view file that generates the actual JavaScript code that will be sent and executed on the client side (or name the JavaScript file check_coupon_code.js.coffee if you're using CoffeeScript).

Updating with JavaScript

The JavaScript in your check_coupon_code.js.erb file will then update the price in your order form.

WARNING: Even if you use JavaScript to change the order price on the client-side (i.e. the browser), it is critical to validate the actual price again in the back-end (i.e. in your controller) in case some malicious user tries to manipulate the browser's request, etc.

You can see the official RailsGuide for another example.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!