2009-07-01 54 views
2

在我的Rails 2.3.2應用Rails的預先​​加載,可能的錯誤

我有2種型號:

class Post 
    has_many :approved_comments, :class_name => 'Comment', :conditions => ['approved => ?', true] 
end 

class Comment 
    belongs_to :post 
end 

出於某種原因,當我嘗試渴望負荷我的意見,我得到一個錯誤

post = Post.find(:first, :conditions => ["permalink=?", permalink], :include => :approved_comments 
 
undefined method `loaded?' for # 

從association_preload.rb線編輯228

這是一個已知問題,還是我做錯了什麼或不支持?

我似乎找到了在這個略一商量:http://groups.google.com/group/maine-ruby-users-group/browse_thread/thread/796cf58b62f9bc52

+0

對條件使用散列比較安全::conditions => {:approved => true}和:conditions => {:permalink => permalink}。我是更多的數據庫不可知論者。 – klew 2009-07-01 11:28:31

+0

您也可以使用Post.first(:conditions ...)而不是Post.find(:first,....)。並且還考慮使用named_scopes來查找已批准的評論 – klew 2009-07-01 11:30:37

回答

1

FWIW,

我想我可能已經在這裏搞砸了,我已經approved_comments在我的類中定義了兩次。我發現的不幸的副作用是急切的加載過濾和進入左連接地獄。所以我通過選擇所有內容並在代碼中過濾來解決它。

0

你可以嘗試這樣的:

class Post 
    has_many :approved_comments, :class_name => 'Comment' 
end 

class Comment 
    belongs_to :post 
end 

,然後是這樣的:

Post.find(:all, :joins => :approved_comments, :conditions => ["comments.approved = ? AND permalink = ?", true, permalink], :include => :approved_comments) 

這將找到所有你想要,然後渴望負荷爲他們的評論文章。在一個大的記錄集,我會建議反對它,但它會很慢,並吹出你的乘客/雜種實例的內存大小。