Reputation: 179
I have this error with my a link in my views
HTML
<% if logged_in? %>
<%=link_to "View Your Cart", cart_path(@cart)%>
<% end %>
my routes
resources :users
resources :parts
resources :carts
resources :categories
resources :line_items
I have this method here to assign a cart to a user
def set_cart
@cart = Cart.find_by(id: session[:cart_id], user: session[:user_id])
rescue ActiveRecord::RecordNotFound
@cart = Cart.create
session[:cart_id] = @cart.id
end
Here is my sessions controller
def new
@user = User.new
end
def create
if params[:provider] == "facebook"
user = User.from_omniauth(env["omniauth.auth"])
session[:user_id] = user.id
redirect_to root_path
else
@user = User.find_by(email: params[:user][:email])
@user = User.new if @user.blank?
if @user && @user.authenticate(params[:user][:password])
session[:user_id] = @user.id
@cart = Cart.create
@user.cart = @cart.id
@user.save
redirect_to @user
else
flash[:notice] = "Failed to login, please try again"
render 'new'
end
end
end
def destroy
session[:user_id] = nil
redirect_to root_url
end
end
And here is my Cart controller
class CartsController < ApplicationController
before_action :set_cart, only: [:show, :edit, :update, :destroy]
rescue_from ActiveRecord::RecordNotFound, with: :invalid_cart
def show
@cart = Cart.find(params[:id])
end
def edit
@cart = Cart.new(cart_params)
end
def update
@cart = Cart.find(params[:id])
if @cart.update_attributes(cart_params)
redirect_to @cart
end
end
def destroy
@cart.destroy if @cart.id == session[:cart_id]
session[:cart_id] = nil
respond_to do |format|
format.html { redirect_to root_path }
format.json { head :no_content }
end
end
private
def cart_params
params.require(:cart).permit(:user_id)
end
def invalid_cart
logger.error "Attempt to access invalid cart #{params[:id]}"
redirect_to root_path, notice: "Invalid cart"
end
end
The following error "No route matches {:action=>"show", :controller=>"carts", :id=>nil} missing required keys: [:id]" rises up when a user signs into their account. What I want is for a user to have a "View Your Cart link" when they log in (inside the layout views) so they can view their cart anywhere. However this error raises once they log in. Any help with this one is appreciated and I'm happy to provide more info.
Upvotes: 1
Views: 2669
Reputation: 6438
Try switching
Cart.find_by(id: session[:cart_id], user: session[:user_id])
with
Cart.find_by!(id: session[:cart_id], user: session[:user_id])
find_by
returns nil
if no record was found. find_by!
throws ActiveRecord::RecordNotFound
error.
Refer to ActiveRecord::FinderMethods for more info.
Upvotes: 1