Sammy Sammy - 3 months ago 7
Ruby Question

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

I am trying to redirect a user, after having created a new 'cupboard' to the user_cupboard_path. I keep getting a

missing required keys[:id]
error

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


This is the params the error screen is giving me

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


cupboards controller

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


routes

resources :users do
resources :cupboards
end


The record is being created through because I can manually type in the URL

localhost3000/users/:id/cupboards/:id


I have tried to do the following in the
redirect_to
statement...

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)


None have worked

I'm certain it's just a newbie mistake, something simple i'm overlooking. Any help is appreciated!

Sam

Answer

Assuming User has_many Cupboards, you should modify your create action.

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