Rails活动记录关联,嵌套模型

时间:2014-07-23 06:47:30

标签: ruby-on-rails associations model-associations

经历过http://guides.rubyonrails.org/association_basics.html,但似乎无法理解这个

我有4个模型:用户,列表,评论,评论回复。有人创建了一个列表,其他人可以对列表进行评论,然后原始创建者可以回复评论。

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 个答案:

答案 0 :(得分:1)

<强>协会

我不会为CommentResponse使用单独的模型;将其全部保存在Comment模型中 - 使用ancestry之类的gem将parent / child系统提供给不同的comments

enter image description here

上面是我们Category模型中的一个示例 - 显示了如何订购与ancestry gem类似的不同关联。我发布的原因是因为这是您为评论创建回复的方式,而不是单独的模型:

#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定义行的父级。许多人认为你必须只定义父母&#34 ;;不对。你必须定义整个&#34;历史&#34;一个对象的祖先

-

<强>树

如果您采用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>

我知道这不是你问题的直接答案;它当然应该对你有所帮助