Note that there are some explanatory texts on larger screens.

plurals
  1. PORelationship between models in Ruby on Rails
    text
    copied!<p>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 :) </p> <p>I currently have 3 models: Group, Post and Comment. Here's the code: </p> <pre><code>class Group &lt; ActiveRecord::Base attr_accessible :affiliation, :group_name, :group_type, :string validates :group_name, :presence =&gt; true has_many :posts, :dependent =&gt; :destroy, :foreign_key =&gt; "id" end class Post &lt; ActiveRecord::Base attr_accessible :body, :posted_by, :posted_by_uid validates :body, :presence =&gt; true belongs_to :group has_many :comments, :dependent =&gt; :destroy end class Comment &lt; ActiveRecord::Base attr_accessible :body, :commenter belongs_to :post end </code></pre> <p>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.</p> <p>Here's the snippet from Show view:</p> <pre><code>&lt;b&gt;Posts&lt;/b&gt; &lt;%= render @group.posts %&gt; </code></pre> <p>Posts partial (_post.html.erb in Posts forlder)</p> <pre><code>&lt;h1&gt;New post&lt;/h1&gt; &lt;%= render 'form' %&gt; &lt;p&gt; &lt;b&gt; Content &lt;/b&gt; &lt;%= @post.body %&gt; &lt;/p&gt; &lt;h2&gt;Comments&lt;/h2&gt; &lt;%= render @post.comments %&gt; &lt;h2&gt;Add a comment:&lt;/h2&gt; &lt;%= render "comments/form" %&gt; &lt;br /&gt; </code></pre> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload