Ruby on Rails: ошибка при попытке добавить товар в корзину (используя позиции) - PullRequest
0 голосов
/ 08 декабря 2018

У меня есть три модели:

Треки, LineItems и Cart

Используя связи позиций, я добавляю треки (для покупки) в корзину.Тем не менее, когда я нажимаю «добавить в корзину», появляется следующее сообщение об ошибке:

No route matches [POST] "/line_items/1"

Несмотря на тщательный просмотр моего кода;Я не могу найти проблему, это в моем контроллере для line_items?Похоже, что он пытается опубликовать line_item с id = 1, который не существует?

line_items_controller.rb

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

  # GET /line_items
  # GET /line_items.json
  def index
    @line_items = LineItem.all
  end

  # GET /line_items/1
  # GET /line_items/1.json
  def show
  end

  # GET /line_items/new
  def new
    @line_item = LineItem.new
  end

  # GET /line_items/1/edit
  def edit
  end

  # POST /line_items
  # POST /line_items.json
  def create
    @track  = Track.find(params[:track_id])
    @line_item = @cart.add_track(track)

    respond_to do |format|
      if @line_item.save
        format.html { redirect_to @line_item, 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

  # PATCH/PUT /line_items/1
  # PATCH/PUT /line_items/1.json
  def update
    respond_to do |format|
      if @line_item.update(line_item_params)
        format.html { redirect_to @line_item, notice: 'Line item was successfully updated.' }
        format.json { render :show, status: :ok, location: @line_item }
      else
        format.html { render :edit }
        format.json { render json: @line_item.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /line_items/1
  # DELETE /line_items/1.json
  def destroy
    @cart = Cart.find(session[:cart_id])
    @line_item.destroy
    respond_to do |format|
      format.html { redirect_to cart_path(@cart), notice: 'Line item was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_line_item
      @line_item = LineItem.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def line_item_params
      params.require(:line_item).permit(:track_id)
    end
end

carts_controller.rb

class CartsController < ApplicationController
  rescue_from ActiveRecord::RecordNotFound, with :invalid_cart
  before_action :set_cart, only: [:show, :edit, :update, :destroy]

  # GET /carts
  # GET /carts.json
  def index
    @carts = Cart.all
  end

  # GET /carts/1
  # GET /carts/1.json
  def show
  end

  # GET /carts/new
  def new
    @cart = Cart.new
  end

  # GET /carts/1/edit
  def edit
  end

  # POST /carts
  # POST /carts.json
  def create
    @cart = Cart.new(cart_params)

    respond_to do |format|
      if @cart.save
        format.html { redirect_to @cart, notice: 'Cart was successfully created.' }
        format.json { render :show, status: :created, location: @cart }
      else
        format.html { render :new }
        format.json { render json: @cart.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /carts/1
  # PATCH/PUT /carts/1.json
  def update
    respond_to do |format|
      if @cart.update(cart_params)
        format.html { redirect_to @cart, notice: 'Cart was successfully updated.' }
        format.json { render :show, status: :ok, location: @cart }
      else
        format.html { render :edit }
        format.json { render json: @cart.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /carts/1
  # DELETE /carts/1.json
  def destroy
    @cart.destroy if cart.id == session[:cart_id] #hook into current client session instead of user
    session[:cart_id] = nil
    respond_to do |format|
      format.html { redirect_to root-path, notice: 'Cart was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_cart
      @cart = Cart.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def cart_params
      params.fetch(:cart, {})
    end

    def invalid_cart
      logger.error "Attempt to access invalid cart #{params[:id]}"
      redirect_to root_path, notice: "That cart doesn't exist"
    end
end

views> carts> show.html.haml

.keep-shopping.pv1.mt4.has-text-right
  = link_to 'Keep Shopping', tracks_path, class: 'button is-warning'
%hr/
%section.section
  = render(@cart.line_items)
  .columns
    .column
      = button_to 'Empty Cart', @cart, method: :delete, data: { confirm: "Are you sure? " }, class: "button is-danger"
    .column.total.has-text-right
      %h4.title.is-4
        %span.f5.has-text-grey Total:
        = number_to_currency(@cart.total_price)

views> _line_items.html.haml (строка помощника частично)

.columns.align-items-center
  .column.is-1
    = line_item.quantity
  .column.is-2
    %figure.is-128x128.image
      = image_tag(line_item.track.image_url(:thumb))
  .column.is-9
    %strong= line_item.track.name
    .columns.align-items-center
      .content.column.is-9
        = truncate(line_item.track.description, length: 140)
      .column.is-3.has-text-right
        %strong.f4= number_to_currency(line_item.total_price)
.has-text-right
  = link_to 'Remove Item', line_item, method: :delete, data: { confirm: "Are you sure? " }, class: "button is-small mb4"
= succeed "/" do
  %hr/

1 Ответ

0 голосов
/ 08 декабря 2018

Я сталкивался с этой проблемой раньше.Я совершенно определенно из твоей кнопки "Добавить в корзину".Я полагаю, ваш LineItem принадлежит к корзине и продукту.Если это так, когда вы передаете данные своей кнопки на кнопку line_item «добавить в корзину», вы можете также настроить текущую корзину так, чтобы отправлять по обоим идентификаторам.

Если возможно, вы можете поделиться другимифрагменты кода вашей кнопки и ваших отношений.

...