Home>

I'm new to programming.

I have implemented a cart function, but after entering the number on the details screen and pressing the add button to the cart, I want to send a parameter with protein_id and quantity information to the view of cart/show, but a routing error occurs. To do.
Looking at the params, it feels like the data is being sent, but I don't understand why the routing error is occurring. I would appreciate it if you could teach me.

Reference article https://qiita.com/Coolucky/items/89ce3a0f25c9dfdb38c1

routes.rb
resources: carts, only: [: show,: create,: destroy]
  post'/ add_item'=>' carts # add_item'
  post'/ update_item'=>' carts # update_item'
  delete'/ delete_item'=>' carts # delete_item'
cart_items_controller.rb
before_action: set_cart_item, only: [: create,: destroy]
    before_action: set_user
    before_action: set_cart
  end
  def create
    @cart_item = @ cart.cart_items.build (protein_id: params [: protein] [: protein_id], quantity: params [: cart_item] [: quantity])
      if @ cart_item.save
        redirect_to current_cart
      else else
        redirect_to protein_path
      end
    end
  end

  def destroy
    @ cart.destroy
    redirect_to current_cart
  end
  private
  def set_user
    @user = current_user
  end
  def set_cart_item
    @cart_item = current_cart.cart_items.find_by (protein_id: params [: protein_id])
  end
  def set_cart
    @cart = current_cart
  end
application_controller.rb
 def current_cart
    if session [: cart_id]
      current_cart = Cart.find_by (id: session [: cart_id])
      session [: cart_id] = current_cart.id
      current_cart
    else else
      current_cart = Cart.create (user_id: current_user.id)
      session [: cart_id] = current_cart.id
      current_cart = Cart.find_by (id: session [: cart_id])
      current_cart
    end
  end
protein show.html.erb
    <% = form_for (CartItem.new, url: cart_path) do | f |%>
        <% = f.label: quantity, "quantity"%>
        <% = f.select: quantity, [1,2,3,4,5,6,7,8,9,10]%>
        <% = f.hidden_field: protein_id, value: @ protein.id%>
        <% = f.submit "Add to cart", class: "btn cart_btn"%>
      <% end%>
  • Answer # 1

    For post, the path is/carts
    If it is get,/carts/3
    It will be.
    Even though it is post,/carts/3
    I think it is an error because it is.