0

我有一个用户模型、一个帖子模型和一个兴趣模型。


User has_many posts through interests

User has_many interests

Post has_many users through interests

Post has_many interests

Interest belongs to Post

Interest belongs to User  

Application_Controller 如下:

class ApplicationController < ActionController::Base
  before_filter :login_from_cookie
  before_filter :find_user_interests
  helper :all # include all helpers, all the time
  session :session_key => '_blah_session'

  include AuthenticatedSystem   

  def find_user_interests
    @user_interests = current_user ? current_user.interests : []  
    true
  end

end

Application.html.erb 有如下内容:

<%= render :partial => "users/interests", :object => @user_interests %>

_interests.html.erb 部分如下:

ul
  <% unless current_user.nil? then -%>  
    <% @user_interests.each do |interest| -%>
      li<%= interest.post.title %>/li
    <% end %>
  <% end -%>   
/ul    

考虑到这一切,当我在 localhost:3000/posts/1 时,我的部分显示正常,但在 localhost:3000/posts 时,我收到错误,因此在 _interests.html.erb 部分中显示undefined method 'title' for nil:NilClass的行 中出现错误。li<%= interest.post.title %>/li

到底会是什么问题?

TIA

4

1 回答 1

2

这只是意味着其中一个兴趣在另一端没有相关的帖子。很可能它被删除了。这可以通过以下方式防止:

class Post < ActiveRecord::Base
  has_many :interests, :dependent => :destroy
end

与此同时,您应该清理数据库中的孤儿。

编辑:您声称这已经在您的模型中,但如果是这样,则不清楚您如何拥有孤立的兴趣,如错误所示。也许它是在您添加从属子句之前创建的?再次,通过 SQL 删除孤儿,然后重试。如果问题稍后再次出现,您必须在没有回调的情况下删除某处。

关于你的尺寸问题。您可能正在使用current_user.interests.count. 这是由于 Rails 关联的一些魔力。count是运行 SQL 的 Rails 关联上的一种特殊方法。 length只是一个数组方法,告诉您数组中有多少项。Rails 关联有一些特殊的方法,但其余的方法透明地传递给数组对象。

进一步的批评:当你通过时,:object => @user_interests你正在设置一个带有部分名称的变量。所以你可以在部分中引用局部变量interests。但是,您正在引用 @user_interests,因此不需要传递对象。在其他条件相同的情况下,传递对象并使用局部变量可能会更好(它更明确,更像是函数式编程风格),但在这种情况下,您并没有使用它。

最后,从风格上讲,我可能是错的,因为我没有完整的上下文,但一般来说,如果没有登录用户,我会将 logged_in 条件放在模板中,而不是将 user_interests 设置为空数组。这将允许您在模板中引用 current_user.interests.count 并在@user_interests 中独立设置要显示的兴趣(例如,用于分页)。

于 2010-04-02T04:59:12.743 回答