Daði Hall Daði Hall - 3 months ago 7
Ruby Question

undefined local variable or method `product' for #<#<Class:0x007fe77c4f3c68>:0x007fe77c69cb78>

I´m having a problem with an app that I´m building.

in

products/show.html.erb
I have this code to add product to cart.

<%= button_to product_items_path(product_id: product) do %>
<i class="fa fa-shopping-cart"></i>Add to Cart
<% end %>


And it always gives me this error
undefined local variable or method 'product' for #<#<Class:0x007fe77c4f3c68>:0x007fe77c69cb78>

This error is happening in the first line According to Better Error gem

I'am using ActiveAdmin but I'm pretty sure that the error is not appearing because of that.

I'm not sure why this is happening, to me the code seems good but I must be overseeing something.

It would be great if someone could take look and maybe see what I´m not seeing.

This is the `ProductItemsController.rb``

class ProductItemsController < ApplicationController

include CurrentCart

before_action :set_cart, only: [:create]
before_action :set_product_item, only: [:show, :destroy]

def create
product = Product.find(params[:product_id])
@product_item = @cart.add_product(product.id)
if @product_item.save
redirect_to root_url, notice:'Product added to Cart'
else
render :new
end
end

private

def set_product_items
@product_item = ProductItem.find(params[:id])
end

def product_item_params
params.require(:product_item).permit(:product_id)
end

end


And here is the ProductsController.rb

class ProductsController < ApplicationController
before_action :set_product, only: [:show, :edit, :update, :destroy]


def show

end

private

def set_product
@product = Product.find(params[:id])
end

def product_params
params.require(:product).permit(:name, :description, :price_usd, :price_isl, :image, :category_id)
end


end

this is the
routes.rb
file

Rails.application.routes.draw do

resources :categories
resources :labels
resources :products

resources :carts
resources :product_items

devise_for :admin_users, ActiveAdmin::Devise.config
ActiveAdmin.routes(self)
root 'pages#index'

Answer

Only instance variables are available to the view.

def create
    @product      = Product.find(params[:product_id]) # Prefix variable name with @
    @product_item = @cart.add_product(product.id)

    if @product_item.save
        redirect_to root_url, notice:'Product added to Cart'
    else
        render :new
    end
end

And your view:

<%= button_to product_items_path(@product) do %>
    <i class="fa fa-shopping-cart"></i>Add to Cart
<% end %>

You should be able to just pass in the object to the _path helper.