Rails将modal与create动作连接起来

时间:2015-07-23 13:01:24

标签: ruby-on-rails ruby twitter-bootstrap

这是我的第一篇文章。我是Rails的新手,我需要你的帮助。我试着在网上开店。 我创建了一个按钮" Buy" (使用bootstrap)在我的每个产品下,激活模态。内部模态是一个按钮"添加到购物车",我不能让它工作。我想通过line_items_controller中的create action添加一个line_item到购物车。模态工作正常,但按钮"添加到购物车"没有。 我认为问题是我给按钮的路径。

我的代码:

cart.rb

class Cart < ActiveRecord::Base
  has_many :line_items, dependent: :destroy

line_item.rb

class LineItem < ActiveRecord::Base
  belongs_to :product
      belongs_to :cart

product.rb

class Product < ActiveRecord::Base
  has_many :line_items

line_items_controller.rb

class LineItemsController < ApplicationController
  include CurrentCart
  before_action :set_cart, only: [:create]
  before_action :set_line_item, only: [:show, :edit, :update, :destroy]

       def create
            @product = Product.find(params[:product_id])
            @line_item = create_line_items(@product)
            respond_to do |format|
              if @line_item.save
                format.html { redirect_to @line_item.cart, notice: 'Line item was successfully created.' }
                format.json { render :show, status: :created, location: @line_item }
              else
                format.html { render :new }
                format.json { render json: @line_item.errors, status: :unprocessable_entity }
              end
            end
          end

      private
        def set_line_item
          @line_item = LineItem.find(params[:id])
        end

        def line_item_params
          params.require(:line_item).permit(:product_id, :cart_id)
        end

应用程序/控制器/关切/ current_cart.rb

module CurrentCart
  extend ActiveSupport::Concern

  def create_line_items(product)
     @cart.line_items.build(product: product)
  end

private

  def set_cart 
    @cart = Cart.find(session[:cart_id])
    rescue ActiveRecord::RecordNotFound
    @cart = Cart.create
    session[:cart_id] = @cart.id
  end
end

application.html.erb中的模态

<div class="modal fade" id="buyModal" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                <p>Are you sure you want to buy this?</p>

                <%= button_to 'Add to cart', line_items_path(product_id: @product), :class => "btn btn-success glyphicon glyphicon-plus", data: {dismiss: "modal"} %>
            </div>
        </div>
    </div>
</div>

按钮&#39;购买&#39;触发模态。

视图/产品/ index.html.erb

<%= link_to 'Buy', '#', class: "btn btn-success active", data: { toggle: "modal", target: "#buyModal"}  %>

我真的很感激任何帮助!

1 个答案:

答案 0 :(得分:0)

在我看来,方法类型存在问题。尝试使用&#39;:method =&gt; :交&#39;使用button_to标记。

<%= button_to 'Add to cart', line_items_path(product_id: @product), :method => :post, :class => "btn btn-success glyphicon glyphicon-plus", data: {dismiss: "modal"} %>