【问题标题】:Render a view of controller A in every view of controller B via Ajax in rails通过 Rails 中的 Ajax 在控制器 B 的每个视图中渲染控制器 A 的视图
【发布时间】:2015-04-08 00:21:35
【问题描述】:

我有一个购物车控制器和一个显示购物车内容的“显示”视图。我想在我的 Products 控制器的每个视图中显示购物车。所以,我正在使用

在 products/show 中渲染购物车/show
<%= render "/cart/show" %>

现在,当用户想要添加产品时,我想通过 ajax 更新购物车。请指导我如何设计我的控制器来实现这一点。

【问题讨论】:

    标签: javascript ruby-on-rails ajax ruby-on-rails-4


    【解决方案1】:

    如何使用局部视图来干燥您的视图。 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")
        }
      });
    

    在轨道控制器中:

    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
    

    显然你的逻辑会有所不同。

    【讨论】:

      最近更新 更多