我收到了错误
No route matches {:action=>"new", :controller=>"lists", :user_id=>nil} missing required keys: [:user_id]
我有一个用户,当该用户登录系统时,他/她可以创建项目列表。现在我根据我的理解,代码是对的,无法弄清楚问题。
我在这里张贴了可能有助于解决问题的代码
这是我的代码 的的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
列表/ 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>
答案 0 :(得分:1)
如果您只希望登录用户仅修改他们拥有的列表,则无需将lists
资源嵌套到users
中,因此请修改您的routes.rb,使其具有:
resources :lists , only: [:index, :new, :create] do
resources :items, only: [:new, :create]
end
如果你有这个,现在应该使用返回当前登录用户的current_user
助手(如果用户未登录则使用nil
)而不是设置@user
实例变量,因此您需要将控制器中的@user
更改为current_user
,例如:
@list = current_user.lists.new
最后一件事,你应该改变你的链接,使它们不再与user
相关:
<%= link_to "Add list", new_list_path, remote: true, class: "btn btn-primary" %>