简体   繁体   English

Ruby on Rails中的模型之间的关系

[英]Relationship between models in Ruby on Rails

I'm new to Rails and working on my first app. 我是Rails的新手,正在开发我的第一个应用程序。 What I want to achieve is an facebook like groups with their own walls and comments. 我要实现的是一个像Facebook一样的团体,他们都有自己的墙和评论。 Sounds pretty easy :) 听起来很简单:)

I currently have 3 models: Group, Post and Comment. 我目前有3种模型:组,帖子和评论。 Here's the code: 这是代码:

class Group < ActiveRecord::Base
  attr_accessible :affiliation, :group_name, :group_type, :string

  validates :group_name, :presence => true
  has_many :posts, :dependent => :destroy, :foreign_key => "id"
end

class Post < ActiveRecord::Base
  attr_accessible :body, :posted_by, :posted_by_uid

  validates :body, :presence => true
  belongs_to :group
  has_many :comments, :dependent => :destroy
end

class Comment < ActiveRecord::Base
  attr_accessible :body, :commenter

  belongs_to :post
end

I managed to properly relate Comments to Posts. 我设法正确地将评论与帖子相关联。 Its views are OK. 它的观点还可以。 But when I tried to relate Posts to Groups for some reason Posts (with corresponding Comments) are not Showing up. 但是当我出于某种原因试图将帖子与组关联时,帖子(带有相应的注释)没有显示。

Here's the snippet from Show view: 这是“显示”视图中的摘录:

<b>Posts</b>
<%= render @group.posts %>

Posts partial (_post.html.erb in Posts forlder) 部分帖子(帖子推荐中的_post.html.erb)

<h1>New post</h1>
<%= render 'form' %>

<p>
  <b> Content </b>
  <%= @post.body %>
</p>

<h2>Comments</h2>
<%= render @post.comments %>  

<h2>Add a comment:</h2>
<%=  render "comments/form" %>
<br />

PS I have no idea why I added foreign key, but without it i would get error (column group.posts.id doesn't exist), I just somehow figured it out comparing with other questions on stackoverflow that foreign key might choose the problem. PS我不知道为什么要添加外键,但是没有它我会报错(column group.posts.id不存在),我只是以某种方式将其与stackoverflow上的其他问题进行了比较,即外键可能会选择问题。 It did, but it's not showing Posts. 确实有,但没有显示帖子。

Make sure that the posts table has a column group_id , then you should be able to remove the foreign key part. 确保posts表具有一列group_id ,那么您应该能够删除外键部分。

If @group doesn't have any posts then it won't render the partial. 如果@group没有任何帖子,则不会呈现该部分内容。 Calling @group.posts will return an array, which is then iterated over and render is called for each object. 调用@group.posts将返回一个数组,然后对其进行迭代,并为每个对象调用render。 If there are no posts then an empty array is returned, and the partial won't be rendered. 如果没有帖子,那么将返回一个空数组,并且不会渲染该部分数组。

Change it to the following: 将其更改为以下内容:

groups#show view: 组#显示视图:

<h1>New post</h1>
<%= render 'posts/form' %>

<b>Posts</b>
<%= render @group.posts %>

_post.html.erb partial: _post.html.erb部分:

<p>
  <b> Content </b>
  <%= @post.body %>
</p>

<h2>Comments</h2>
<%= render @post.comments %>  

<h2>Add a comment:</h2>
<%= render "comments/form" %>
<br />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM