Hi I want to create an ec site and try to make quantity system.
What I want to do: Adding a item in quantity of CreateBasketItems(2021_create_basket_items.rb)
Question: How can I write some code in item/show.html.erb which is part of form_with() in particular?
2021_create_basket_items.rb
class CreateBasketItems < ActiveRecord::Migration[5.2]
def change
create_table :basket_items do |t|
t.references :basket, index: true, null: false, foreign_key: true
t.references :item, index: true, null: false, foreign_key: true
t.integer :quantity, null: false, default: 1
t.timestamps
end
end
end
item/show.html.erb
The url: show.html.erb => item_controller.rb/create
<%= form_for url: item_add_to_baskets_path(@item,@basket_item), method: :post do |f| %>
<%= f.select :quantity,[1,2,3], id: "country1", class: "frm-field required sect" %>
<%= f.submit "add to basket", class: "item_add" %>
<% end %>
just in case the error is.
ArgumentError (wrong number of arguments (given 1, expected 0)):
item_controller.rb
class ItemsController < ApplicationController
# before_action :authenticate_user!
def show
basket = current_user.prepare_basket
@item = Item.find(params[:id])
@basket_item = basket.basket_items(params[:quantity])
end
def index
# if(params[:category])
# @items = Item.where(category: params[:category]).paginate(page: params[:page])
# else
# @items = Item.paginate(page: params[:page])
# end
@items = (params[:category]) ? Item.where(category: params[:category]).paginate(page: params[:page]) :
Item.paginate(page: params[:page])
end
end
add_to_basket_controller.rb
class Items::AddToBasketsController < Items::ApplicationController
def create
basket = current_user.prepare_basket
@item = Item.find(params[:item_id])
@basket_item = basket.basket_items(params[:quantity])
basket.basket_items.create!(item_id: @item.id, quantity: @basket_item)
flash[:success] = "your item in basket"
redirect_to baskets_path
end
end
There are a couple of issues with the code.
basket.basket_items
doesn't expect any arguments but you're passing one. In fact, you don't need that line of code at all. Remove it.
You're not passing the right quantity to the create!
call.
basket.basket_items.create!(item_id: @item.id, quantity: params[:quantity])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.