Ruby on Rails рендеринг объекта с помощью ajax - PullRequest
0 голосов
/ 08 мая 2019

Я следую книге Agile Web Development с Rails 5.1 и нахожусь в главе 11, где я пытаюсь создать кнопку, которая уменьшает количество товара в моей корзине. Я пытаюсь использовать ajax для решения этой проблемы и вызываю метод рендеринга в корзине. Я получаю следующую ошибку ...

ActionView :: Template :: Error ('nil' не является ActiveModel-совместимым объектом. Он должен реализовывать: to_partial_path.): 1: корзина = document.getElementById ("корзина") 2: cart.innerHTML = "<% = j render (@cart)%>"

кнопка, из которой вызывается этот ajax, является частичной, если это что-то меняет. Я новичок в рельсах и застрял.

decrement_quantity.js.coffee

cart = document.getElementById("cart")
cart.innerHTML = "<%= j render(@cart) %>"

_line_item.html.erb

<% if line_item== @current_item %>
<tr class="line-item-highlight">
<% else %>
<tr>
<% end %>
  <td id="quantity"><%= line_item.quantity %></td>
  <td><%= line_item.product.title %></td>
  <td id="price" class="price"><%= number_to_currency(line_item.total_price) %></td>
  <td><%= button_to 'X', line_item, method: :delete, data: {confirm: 'Are you sure?' } %></td>
  <td id="decrement_quantity"><%= button_to '-1', line_items_decrement_quantity_path(id: line_item.id), remote: true%></td>
</tr>

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, :decrement_quantity]
.
.
.
  def decrement_quantity
    if @line_item.quantity > 1
      @line_item.quantity -= 1
      @line_item.save
    else
      @line_item.destroy
    end
    respond_to do |format|
      format.html { redirect_to store_index_url, notice: 'Line item was successfully decremented.' }
      format.js {}
      format.json { head :no_content }
    end
  end
.
.
.

routes.db

Rails.application.routes.draw do
  resources :line_items
  resources :carts
  #get 'store/index'
  root 'store#index', as: 'store_index'

  post 'line_items/decrement_quantity'

  resources :products
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

Я не уверен, что мне что-то не хватает, но та же команда ajax с другой кнопки в другом представлении работает нормально. Любой, кто поможет мне, высоко ценится:)

1 Ответ

0 голосов
/ 08 мая 2019

Вы не установили @cart, что означает, что ваше представление выполняет "<%= j render(nil) %>".

Ваш контроллер устанавливает @cart только через предварительное действие, которое выполняется только до действия create:

  before_action :set_cart, only: [:create]

Если вы хотите, чтобы decrement_quantity выдвигал переменную @cart в представление, вам нужно либо расширить параметр only:, чтобы включить [:create, :decrement_quantity] (который может работать, а может и не работать).вы не включили содержимое этого метода в свой вопрос) или явно указали @cart внутри действия decrement_quantity.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...