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.
David E. (Guest)
on 2007-03-16 14: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.
David E. (Guest)
on 2007-03-16 14:20
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.
Ilan B. (Guest)
on 2007-03-16 16:45
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. (Guest)
on 2007-03-16 16:47
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..
This topic is locked and can not be replied to.