没有路由匹配{:action =>" show",:controller =>"橱柜",:user_id =>" 19"}缺少必需的密钥: [:ID]

时间:2016-08-17 16:16:53

标签: ruby-on-rails ruby

我正在尝试在创建新的橱柜后重定向用户'到user_cupboard_path。我一直收到missing required keys[:id]错误

No route matches {:action=>"show", :controller=>"cupboards", :id=>nil, :user_id=>nil} missing required keys: [:id, :user_id]

这是错误屏幕给我的参数

   {"utf8"=>"✓",
 "authenticity_token"=>"MmxYdBmGHgMTcyw3fVz0/Lmw7TbFtOxDlKKEDtbPTZgfger08QSGxc4+1qkEXOLzurDne+55V6SUBqXAx+g==",
 "style"=>"ATHLEISURE",
 "commit"=>"Create Cupboard",
 "user_id"=>"19"}

橱柜控制器

def create
  @cupboard = Cupboard.new(cupboard_params)
 if @cupboard.save
   redirect_to user_cupboard_path(@cupboard)
 else
   render :new
 end
end

路由

resources :users do
 resources :cupboards
end

正在创建记录,因为我可以手动输入URL

localhost3000/users/:id/cupboards/:id

我已尝试在redirect_to声明中执行以下操作...

redirect_to user_cupboard_path(@cupboard)
redirect_to user_cupboard_path(@user)
redirect_to user_cupboard_path(@user, @cupboard)
redirect_to user_cupboard_path(cupboard)
redirect_to user_cupboard_path(user)

没有工作

我确定这只是一个新手的错误,我可以忽略一些简单的事情。任何帮助表示赞赏!

萨姆

2 个答案:

答案 0 :(得分:2)

假设User has_many Cupboards,您应该修改您的创建操作。

def create
  @user = User.find(params[:user_id])
  @cupboard = @user.cupboards.new(cupboard_params)
 if @cupboard.save
   redirect_to user_cupboard_path(@cupboard)
 else
   render :new
 end
end

答案 1 :(得分:0)

好的,问题已解决,主要得益于Pramod

将我的控制器更改为

  def create
  @user = User.find(params[:user_id])
  @cupboard = @user.cupboards.new(cupboard_params)
 if @cupboard.save
   redirect_to user_cupboard_path(@user, @cupboard)
 else
   render :new
 end
end

此外,Pramod让我第二次猜测我的模型设置。事实证明我也忘了在我的用户模型中有has_many :users