2014-07-23 108 views
1

正在經歷http://guides.rubyonrails.org/association_basics.html但似乎無法讓我解決這個Rails的活動記錄的關聯,嵌套模型

的頭,我有4種型號:用戶列表,評論,commentresponses。有人創建列表,其他人可以對列表發表評論,然後原始創建者可以對評論做出迴應。

class User < ActiveRecord::Base 
    has_many :comments, foreign_key: 'provider' 
    has_many :listings 
    has_many :comments 
    has_many :commentresponses 
end 

class Listing < ActiveRecord::Base 
    belongs_to :user 
end 

class Comment < ActiveRecord::Base 
    belongs_to :listing 
    belongs_to :user 
    has_one :commentresponse 
end 

class Commentresponse < ActiveRecord::Base 
    belongs_to :comment 
    belongs_to :user 
end 

一切運轉良好,除非我無法訪問comment.commentresponse;這給了一個沒有方法的錯誤。

任何關於我的邏輯錯誤的建議?

+1

這段代碼看起來不錯,你可以粘貼確切的錯誤信息? –

回答

1

協會

我不會使用CommentResponse一個單獨的模型;讓這一切在Comment模型 - 使用的寶石,如ancestry給予parent/child系統不同comments

enter image description here

以上是例如,一個我們Category車型 - 顯示你如何可以訂購與ancestry寶石之類的不同關聯。爲什麼我張貼的原因是因爲這是如何創建迴應您的意見,而不是一個單獨的模型:

#app/models/user.rb 
class User < ActiveRecord::Base 
    has_many :listings 
    has_many :comments 
end 

#app/models/listing.rb 
class Listing < ActiveRecord::Base 
    belongs_to :user 
end 

#app/models/comment.rb 
class Comment < ActiveRecord::Base 
    belongs_to :listing 
    belongs_to :user 

    has_ancestry #-> make sure you have "ancestry" column with string in db 
end 

這基本上可以讓你使用哪個ancestry附加到你的對象various methods

enter image description here


祖先

我會推薦使用Ancestry gem來存儲評論的回覆。然後,您可以使用幾個partials添加到此以提供嵌套的界面。通過這種方式,它會告訴你你想要的意見,並在正確的反應等

重要

使用ancestry - 定義行的家長comment_1/comment_2。許多人認爲你必須定義「父母」;不對。你必須定義一個對象的祖先的整個「歷史」

-

如果用ancestry方法去,你就可以做一些事情,如以下:

enter image description here

要做到這一點,你可以使用我們這裏創建的嵌套的部分(顯然與評論使用替換):

#app/views/categories/index.html.erb 
<%= render partial: "category", locals: { collection: @categories } %> 

#app/views/categories/_category.html.erb 
<ol class="categories"> 
    <% collection.arrange.each do |category, sub_item| %> 
     <li> 
      <!-- Category --> 
      <div class="category"> 
       <%= link_to category.title, edit_admin_category_path(category) %> 
      </div> 

      <!-- Children --> 
      <% if category.has_children? %> 
       <%= render partial: "category", locals: { collection: category.children } %> 
      <% end %> 

     </li> 
    <% end %> 
</ol> 

我知道這是不是一個直接回答你的問題;它當然應該可以幫你,雖然

+1

+1對於評論回覆沒有單獨的模型 – sevenseacat

+0

感謝 - 這是最好的方式 –

+0

感謝里克,欣賞這一建議。我看看祖先。在多層評論的情況下,你會推薦以下內容:第一條評論:Comment.create(評論:「你失敗了」)。第一反應:評論(1).children.create(評論:「不,我真的通過了」)。第二個響應(對響應的響應):評論(2).children.create(評論:「不,你真的失敗了」)。等等? – dmt2989

相關問題