Я пытаюсь создать корзину для пользователя.Он основан на приложении Flanger из веб-анализа, ассоциация:
cart has many line items
item has many line items
line item belongs to item
line item belongs to cart
в модели Cart, я создал метод add_item:
def add_item(item)
current_item = line_items.find_by(item_id: item.id)
if current_item
current_item.increment(:quantity)
else
current_item = line_items.build(item_id: item.id)
end
current_item
end
для контроллера line_items, сгенерированкомандой "rails g scaffold"
в line_items_controller.rb:
before_action :set_line_item, only: [:show, :edit, :update, :destroy]
before_action :set_cart, only: [:create]
def index
@line_items = LineItem.all
end
def show
end
def new
@line_item = LineItem.new
end
def create
item = Item.find(params[:item_id])
@line_item = @cart.add_item(item)
respond_to do |format|
if @line_item.save
format.html { redirect_to @line_item.cart, notice: 'Item added' }
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(:item_id)
end
Для модуля current_cart:
def set_cart
@cart = Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
@cart = Cart.create
session[:cart_id] = @cart.id
end
в Item / show.html.erb,Я создаю кнопку для добавления текущего элемента в корзину:
<%= button_to "Add to cart" ,line_item_path(item_id: @item),class:'btn btn-success'%>
в rout.rb:
resources :line_items
resources :carts
resources :items
Так что ошибка появляется всякий раз, когда я нажимаю кнопку «Добавить в корзину»,Я ищу решения для решения этой проблемы.