简体   繁体   中英

Render a view of controller A in every view of controller B via Ajax in rails

I have a Cart controller and a "show" view which shows the contents of the cart. I want to show the cart in every view of my Products controller. So, I'm rendering the cart/show in products/show using

<%= render "/cart/show" %>

Now, I want to update the cart via ajax when a user wants to add a product. Please guide me how I should design my controllers to achieve this.

How to use partials to DRY up your views. http://guides.rubyonrails.org/layouts_and_rendering.html

function postToRailsApi() {
  $.ajax({
    type: "POST",
    url: "the_url_you_want_to_post_to/endpoint",
    data: {someData: {thisId: otherId}},
    dataType: "json",
    success: function(data) {
      alert("OMG SUCCESS status:200")
    }
  });

In the rails controller:

respond_to do |format|
      if @my_condition.save
        format.html {render nothing: true, status:200}
        format.js{render nothing: true, status:200}
        format.json { render json: @timestamp, status: 200 }
      else
        format.html { render action: "new" }
        format.js { render nothing: true, status: 400 }
        format.json { render nothing: true, status: 400 }
      end
    end

Obviously your logic will be different.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM