Models and relationships

If I have three models; Post, Comment, and User, and they are all set up
according to Rails naming conventions, and I have established their
relationships in the model code as follows:

class Post < ActiveRecord::Base
has_many :comments
end

class User < ActiveRecord::Base
has_many :comments
end

class Post < ActiveRecord::Base
belongs_to :post
belongs_to :user
end

Then should I be able to do something like this?

01 <% for post in @posts %>
02 <% for comment in post.comments %>
03 <%= comment.user.username %>
04 <% end %>
05 <% end %>

It’s line 03 that’s causing me a problem, as it generates an “undefined
method ‘user’ for #Comment:0xHEX” error. Replacing that line with
User.find(comment.user_id).username works, but Im not sure if I should
be doing it that way or not.

David E. wrote:

class Post < ActiveRecord::Base
belongs_to :post
belongs_to :user
end

Ignore my poor copy and pasting, that should be class Comment.

David E. wrote:

class Post < ActiveRecord::Base
belongs_to :post
belongs_to :user
end

Then should I be able to do something like this?

01 <% for post in @posts %>
02 <% for comment in post.comments %>
03 <%= comment.user.username %>
04 <% end %>
05 <% end %>

It’s line 03 that’s causing me a problem, as it generates an “undefined
method ‘user’ for #Comment:0xHEX” error. Replacing that line with
User.find(comment.user_id).username works, but Im not sure if I should
be doing it that way or not.

According to your model structure, each post has only one comment… so
it’s post.comment not post.comments…

hope this helps…

ilan

Ilan B. wrote:

David E. wrote:

According to your model structure, each post has only one comment… so
it’s post.comment not post.comments…

hope this helps…

ilan

Whoops… missed the edit… sorry…