IWI
IWI

Reputation: 1604

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

Upvotes: 0

Views: 119

Answers (2)

IWI
IWI

Reputation: 1604

Alright, problem fixed, mainly thanks to Pramod

Changed my controller to

  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

Additionally, Pramod made me second guess my model setup. Turns out I also forgot to have a has_many :users in my User model.

Upvotes: 0

Pramod
Pramod

Reputation: 1416

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

Upvotes: 2

Related Questions