I am just beginning to work with Rails. I have a model, “User” and it has many “List”. On the user show view I have created a form to create a list for the current user. When the form is submitted I get the following error:
Couldn’t find User without an ID
I assume that there is something wrong with the way I have setup the nested List form.
User -> show.html.erb
<p id="notice"><%= notice %></p>
<p>
<b>Username:</b>
<%= @user.username %>
</p>
<p>
<b>Password:</b>
<%= @user.password %>
</p>
<p>
<b>Email:</b>
<%= @user.email %>
</p>
<h2>Add a List</h2>
<%= form_for([@user, @user.lists.build]) do |f| %>
<div class ="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="field">
<%=f.label :description%><br />
<%=f.text_field :description%>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
<%= link_to 'Edit User', edit_user_path(@user) %> |
<%= link_to 'Back to Users', users_path %>
This is the list ‘create’ controller action.
class ListsController < ApplicationController
def create
@user = User.find(params[:id])
@list = @user.lists.create(params[:list])
redirect_to user_path(@user)
end
end
Update: show method on UserController
# GET /users/1
# GET /users/1.json
def show
@user = User.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @user }
end
end
Update: My routes
resources :users do
resources :lists
end
get "home/index"
So is params[:id] nil somehow? What am I missing?
Thanks!
Make sure you are using
params[:user_id]in create action, notparams[:id]