【问题标题】:has_many through and partialshas_many through 和 partials
【发布时间】:2010-04-03 03:00:21
【问题描述】:

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


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 时,我收到错误 undefined method 'title' for nil:NilClass,因此在上面显示的 li&lt;%= interest.post.title %&gt;/li 行中出现错误_interests.html.erb 部分。

这到底是什么问题?

TIA

【问题讨论】:

    标签: ruby-on-rails partials


    【解决方案1】:

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

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

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

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

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

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

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

    【讨论】:

    • 我通过 has_many :interest, :dependent => :destroy 覆盖了 Posts 模型
    • 另外奇怪的是,如果我取出显示标题的部分代码来解决这个错误。我的部分标题设置为“您有@user_interests.length 兴趣”,当我在帖子页面上并说帖子页面有 10 个帖子时,我的标题读为“您有 10 个兴趣”,所以它计数所有即使用户没有选择帖子作为兴趣,也将帖子作为兴趣。
    • 当我转到一个特定的帖子页面时,请显示操作,在该页面上,上面引用的标题显示为“您有 1 个兴趣”,因此它似乎在计算特定页面上的帖子数量(索引或显示)并将它们汇总为用户的兴趣。
    • 哎呀,对不起,我倒置了从属子句。如果你确实有你所说的,那么目前还不清楚这是怎么发生的。更多 cmets 正在编辑中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    • 2011-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    相关资源
    最近更新 更多