我的观点中的链接出现此错误
HTML
<% if logged_in? %>
<%=link_to "View Your Cart", cart_path(@cart)%>
<% end %>
我的路线
resources :users
resources :parts
resources :carts
resources :categories
resources :line_items
我在这里使用此方法为用户分配购物车
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
这是我的会话控制器
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
这是我的推车控制器
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
以下错误“无路由匹配{:action =&gt;”show“,:controller =&gt;”carts“,:id =&gt; nil}缺少必需的密钥:[:id]”当用户上升时“登录他们的帐户。我想要的是用户在登录时(在布局视图内)拥有“查看购物车链接”,以便他们可以在任何地方查看他们的购物车。但是,一旦他们登录,这个错误就会引发。对此有任何帮助表示赞赏,我很乐意提供更多信息。
答案 0 :(得分:1)
尝试切换
Cart.find_by(id: session[:cart_id], user: session[:user_id])
与
Cart.find_by!(id: session[:cart_id], user: session[:user_id])
find_by
将返回nil
。 find_by!
引发ActiveRecord::RecordNotFound
错误。
有关详细信息,请参阅ActiveRecord::FinderMethods。