has_many通过和部分

时间:2010-04-02 04:36:07

标签: ruby-on-rails partials

我有一个User模型,一个Post模型和一个Interest模型。


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 partial如下:

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 /帖子时,我收到错误undefined method 'title' for nil:NilClass因此行li<%= interest.post.title %>/li中的错误如上所示_interests.html.erb partial。

问题到底是什么?

TIA

1 个答案:

答案 0 :(得分: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时,您正在设置一个名为partial的变量。因此,您可以在partial中引用局部变量interests。但是,您正在引用@user_interests,因此不需要传递对象。在其他条件相同的情况下,传递对象并使用局部变量可能更好(它更明确,更多的是函数编程风格),但在这种情况下,你没有使用它。

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