ruby-on-rails - 没有路线匹配 {:action=>"show", :controller=>"shops", :id=>nil},缺少必需的键:[:id]
问题描述
我正在构建一个电子商务应用程序,每个用户都可以在其中创建自己的商店。用户和商店之间的关联应该是
user has_one shop
shop belongs_to user
到目前为止,创建商店的用户运行良好。但是对于那些没有的人,它向我显示了一个错误:
No route matches {:action=>"show", :controller=>"shops", :id=>nil}, missing required keys: [:id]
在我的shops_controller.rb
class ShopsController < ApplicationController
before_action :find_shop, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
before_action :find_user
def show
if current_user.shop.blank?
render 'new'
else
@items = Item.where(shop_id: @shop.id)
end
end
def index
@shops = Shop.all.order("created at DESC")
end
def new
@shop = current_user.build_shop
end
def create
@shop = current_user.build_shop(shop_params)
if @shop.save
session[:shop_id] = @shop.id
flash[:success] = "Creating item success"
redirect_to @shop, notice: 'success'
else
render 'new'
end
end
private
def shop_params
params.require(:shop).permit( :name , :user_id)
end
def find_store
@shop = Shop.find(params[:id])
end
def find_user
@user = UrStore.find_by(params[:user_id])
end
end
在application.html.erb
<% if user_signed_in?%>
<%= link_to "profile", user_path(current_user.id) %>
<% if current_user.shop == nil %>
<li><%= link_to "Your shop", new_shop_path %></li>
<% else %>
<li><%= link_to "Your shop", shop_path(current_user.shop.id)%></li>
<% end %>
<% end %>
由current_user
gem 'devise' 自动生成。
单击“您的商店”时发生错误,并且该错误仅发生在未创建其商店的用户身上
在 routes.rb 中:
devise_for :users
root 'static_pages#home'
as :user do
get "signin" => "devise/sessions#new"
post "signin" => "devise/sessions#create"
delete "signout" => "devise/sessions#destroy"
end
resources :shops
此行引发了错误:
<li><%= link_to "Your Shop",shop_path(current_user.shop.id)%></li>
我正在寻找解决这个问题的解决方案:-)
解决方案
当你去new_shop_path
你的控制器动作new
似乎建立一个用户商店:
@shop = current_user.build_shop
所以从这里current_user.shop != nil
但是由于当时没有保存,所以这家店没有id
。因此,在您看来,它进入else
as shop 不是 nil ,但随后没有id
,它会引发错误。
<% if current_user.shop == nil %>
<li><%= link_to "Your shop", new_shop_path %></li>
<% else %>
<li><%= link_to "Your shop", shop_path(current_user.shop.id)%></li>
<% end %>
将其更改为:
<% if !current_user.shop || !current_user.shop.id %>
<li><%= link_to "Your shop", new_shop_path %></li>
<% else %>
<li><%= link_to "Your shop", shop_path(current_user.shop.id)%></li>
<% end %>
推荐阅读
- f# - 来自列表理解的意外返回类型
- python - PyTorch:权重的 Sigmoid?
- crystal-reports - 使用工作日设置到期日
- c++ - 使用 vtkDICOMWriter 写入 DICOM 时访问读取冲突
- php - 我为电子邮件表单联系人编写了一些 jquery、html 和 php 代码,但出现了问题
- android - 在 Android 上使用 Cognito 用户池身份验证为 AWS AppSync 更正 Proguard 规则
- delphi - Firedac 与具有字符集 xxx 的 firebird 2.1 的连接错误
- java - 具有 BluetoothAdapter.ACTION_STATE_CHANGED 动作的广播接收器(奥利奥)
- http-headers - 静态文件的 NestJS 标头
- regex - 用于量化和查找字符的正则表达式