Forum: Ruby on Rails Models and relationships

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
41cfad2064d52a800978b0289a3138a0?d=identicon&s=25 David Edwards (revlob)
on 2007-03-16 13:19
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.
41cfad2064d52a800978b0289a3138a0?d=identicon&s=25 David Edwards (revlob)
on 2007-03-16 13:20
David Edwards wrote:
> class Post < ActiveRecord::Base
>   belongs_to :post
>   belongs_to :user
> end

Ignore my poor copy and pasting, that should be class Comment.
391f9b787cdc12aa2c179713f5103e3a?d=identicon&s=25 Ilan Berci (iberci)
on 2007-03-16 15:45
David Edwards 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
391f9b787cdc12aa2c179713f5103e3a?d=identicon&s=25 Ilan Berci (iberci)
on 2007-03-16 15:47
Ilan Berci wrote:
> David Edwards 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..
This topic is locked and can not be replied to.