【问题标题】:Rails active record associations, nested modelsRails 活动记录关联,嵌套模型
【发布时间】:2014-07-23 06:47:29
【问题描述】:

一直在经历http://guides.rubyonrails.org/association_basics.html,但似乎无法理解这一点

我有 4 个模型:users、listings、cmets、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 之外,一切都运行良好;这给出了一个无方法错误。

我的逻辑哪里错了有什么建议吗?

【问题讨论】:

  • 这段代码看起来不错,你能粘贴准确的错误信息吗?

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


【解决方案1】:

协会

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

以上是我们Category 模型之一的示例 - 展示了如何订购与ancestry gem 之类的不同关联。我发布的原因是因为您可以通过这种方式为您的 cmets 创建响应,而不是使用单独的模型:

#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

这基本上允许您使用various methods ancestry 附加到您的对象:


祖先

我建议使用 Ancestry gem 来存储 cmets 的响应。然后,您可以通过使用多个partials 来提供嵌套接口。这样,它将向您显示您想要的 cmets,以及正确的响应等

重要

使用ancestry 时 - 您使用comment_1/comment_2 定义行的父级。许多人认为您必须定义“父级”;不对。您必须定义对象祖先的整个“历史”

--

如果您采用ancestry 方法,您将能够执行以下操作:

要实现这一点,您可以使用我们在此处创建的嵌套部分(显然替换为与 cmets 一起使用):

#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 表示没有单独的评论回复模型
  • 谢谢 - 这是最好的方法
  • 感谢 Rick,感谢您的推荐。我用工具看看祖先。在多层 cmets 的情况下,您是否会推荐以下内容: 第一条评论:Comment.create(comment: "You failed")。第一反应:comment(1).children.create(comment: "No, I actually pass")。第二个响应(response to response):comment(2).children.create(comment: "nope, you really failed")。等等?
  • 是的 - 我认为这是最好的方法
  • 感谢您的帮助。得到了使用comment.children.create的东西,但似乎无法通过创建新评论并传入:parent_id来使其工作。无论哪种方式,工作解决方案,所以再次感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多