Reputation: 37
I'm new to Rails and working on my first app. What I want to achieve is an facebook like groups with their own walls and comments. Sounds pretty easy :)
I currently have 3 models: Group, Post and Comment. 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)
<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. It did, but it's not showing Posts.
Upvotes: 0
Views: 131
Reputation: 4880
Make sure that the posts table has a column group_id
, then you should be able to remove the foreign key part.
If @group
doesn't have any posts then it won't render the partial. Calling @group.posts
will return an array, which is then iterated over and render is called for each object. 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:
<p>
<b> Content </b>
<%= @post.body %>
</p>
<h2>Comments</h2>
<%= render @post.comments %>
<h2>Add a comment:</h2>
<%= render "comments/form" %>
<br />
Upvotes: 1