Reputation: 167
I'm getting the error
No route matches {:action=>"new", :controller=>"lists", :user_id=>nil} missing required keys: [:user_id]
I have a user and when that user login into the system he/she can create lists of items. Now i cannot figure out the problem as per my understanding the code is right.
I'm posting here my code that may help to get the problem
Here is my code routes.rb
root 'lists#index'
resources :users do
resources :lists , only: [:index, :new, :create] do
resources :items, only: [:new, :create]
end
end
resources :lists, only: [:destroy]
resources :items, only: [:destroy]
get '/signup' => 'users#new'
resources :users
get '/login'=>'sessions#new'
post 'login' => 'sessions#create'
delete 'logout' => 'sessions#destroy'
lists_controller.rb
def index
@lists = List.includes(:items).where(:user_id => session[:user_id]).order('items.priority')
end
def new
@user = User.find(session[:user_id])
@list = @user.lists.new
end
def create
@user = User.find(session[:user_id])
@list = @user.lists.new(list_params)
@list.created_date = DateTime.now
respond_to do |format|
if @list.save
format.json { head :no_content }
format.js
else
format.json { render json: @list.errors.full_messages, status: :unprocessable_entity }
end
end
end
lists/index.html.erb
<div class="container">
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-6"><h2>Lists Homepage</h2></div>
</div>
<div class="well">
<%= link_to "Add List", new_user_list_path(@user), remote: true, class: "btn btn-primary" %>
<% if current_user %>
<%= link_to "Log Out", logout_path, method: "delete", class: "btn btn-primary pull-right"%>
<label class="pull-right"><%= current_user.email %></label>
<% end %>
</div>
<div class="new-list"></div>
<div id="lists">
<%= render @lists || '' %>
</div>
<%= render 'dialog' %>
</div>
Upvotes: 0
Views: 74
Reputation: 51171
If you want only logged in users modify only lists they own, you don't need to nest lists
resources into users
, so modify your routes.rb so it has:
resources :lists , only: [:index, :new, :create] do
resources :items, only: [:new, :create]
end
If you have this, now you should use your current_user
helper that returns currently logged in user (or nil
if user isn't logged in) instead of setting @user
instance variable, so you need to change your @user
to current_user
in your controller, for example:
@list = current_user.lists.new
And the last thing, you should change your links so they aren't related to user
anymore:
<%= link_to "Add list", new_list_path, remote: true, class: "btn btn-primary" %>
Upvotes: 1