【发布时间】:2012-08-15 11:21:03
【问题描述】:
第一个问题,请温柔:)
我在为属于具有 has_many 关联的用户模型的客户端模型创建索引视图时遇到问题。
错误信息:
'nil' is not an ActiveModel-compatible object that returns a valid partial path.
具体的错误是指第11行的部分错误:
/views/clients/index.html
<% provide(:title, current_user.name) %>
<div class="row">
<aside class="span4">
<section>
<h1>Your clients</h1>
</section>
</aside>
<div class="span8">
<% if current_user.clients.any? %>
<ol class="clients">
<%= render @clients %>
</ol>
<%= will_paginate %>
<% end %>
</div>
</div>
/clients/_client.html.erb
<li>
<span class="client-name"><%= client.name %></span>
<span class="client-info">
Extra client info to come.
</span>
</li>
客户端控制器:
class ClientsController < ApplicationController
belongs_to :user
def index
@clients = current_user.clients.paginate(page: params[:page])
end
编辑:
如果有帮助,用户控制器...
class UsersController < ApplicationController
before_filter :authenticate_user!
def show
if current_user.admin?
@user = User.find(params[:id])
else
@user = current_user
end
end
def index
if current_user.admin?
@users = User.paginate(page: params[:page])
else
redirect_to root_path
end
end
def destroy
User.find(params[:id]).destroy
flash[:success] = "User destroyed."
redirect_to users_path
end
end
您可能会说我是 Rails 新手,但我已经搜索以确保尚未涵盖此内容。
【问题讨论】:
-
如果你在控制器的 index 方法中抛出一个调试器,@client 是什么样的?还可以尝试将索引视图中的第 9 行替换为
<% if @clients.present? %>。 -
我在显示
--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess action: index controller: clients的索引视图上使用调试器,不幸的是我不明白“控制器索引方法中的调试器”是什么意思。但是,我在第 9 行尝试了您建议的代码,它显示了一个空索引。但是客户端已经生成并存在于数据库中。 -
更新:我现在可以通过省略部分并添加
<% current_user.clients.each do |client| %>; <%= link_to client.name, client %>来显示正确的索引,但 will_paginate 现在返回The @clients variable appears to be empty. Did you forget to pass the collection object for will_paginate? -
据我所知,实例变量设置不正确?
-
对,您想使用@clients 来迭代部分渲染并将其传递给 will_paginate 辅助方法。
标签: ruby-on-rails ruby-on-rails-3 will-paginate