【问题标题】:'nil' is not an ActiveModel-compatible object that returns a valid partial path“nil”不是返回有效部分路径的 ActiveModel 兼容对象
【发布时间】: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 行替换为 &lt;% if @clients.present? %&gt;
  • 我在显示--- !ruby/hash:ActiveSupport::HashWithIndifferentAccess action: index controller: clients 的索引视图上使用调试器,不幸的是我不明白“控制器索引方法中的调试器”是什么意思。但是,我在第 9 行尝试了您建议的代码,它显示了一个空索引。但是客户端已经生成并存在于数据库中。
  • 更新:我现在可以通过省略部分并添加 &lt;% current_user.clients.each do |client| %&gt;; &lt;%= link_to client.name, client %&gt; 来显示正确的索引,但 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


【解决方案1】:

您应该将:page =&gt; params[:page] 传递给分页吗?

【讨论】:

  • 感谢@Nick,但当前版本与我相信的新哈希符号相同。
  • 啊抱歉——我以前没见过它用过,但后来我只涉足红宝石。
【解决方案2】:

我在客户端控制器和模型中声明了belongs_to,而不仅仅是模型。两天没注意到。

【讨论】:

  • 这解决了问题吗?我完全错过了。我已经使用了相当多的 InheritedResources gem,所以它并没有对我产生影响。第二双眼睛就这么多了。
猜你喜欢
  • 2018-08-04
  • 1970-01-01
  • 1970-01-01
  • 2015-05-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-08
  • 1970-01-01
相关资源
最近更新 更多