views:

33

answers:

1
class Comment < ActiveRecord::Base  
  belongs_to :post  
  belongs_to :user  
end  

So with the above association can I fetch both user and post details from a given comment object?.
like

@comment.post.post_title and  
@comment.user.user_name.  

Also please note that I have used comment as a nested resource of post.

resources :posts do  
   resources :comments  
end  
+3  A: 

Yes you can, and you don't need to specify the foreign key or class name to do so. Saying belongs_to :user means rails will look for a user_id integer field in the comments table, and expect an ActiveRecord class named User to exist.

Add as many as you like, they don't interfere with each other.

Jaime Bellmyer
Is this new as of Rails 3? I certainly had to specify a foreign key to do this in Rails 2.3.2, and I upgraded to Rails 3 so recently that I haven't had the chance to try this.
Samo
No, this isn't new, it goes back as far as 1.2 (the earliest version I used). A model can have any number of associations (has_many, belongs_to, etc) and they don't affect each other. The only time you need to specify class_name and foreign_key is when they're different from what rails would expect.
Jaime Bellmyer
Well that's news to me, since I know I tried this and it didn't work until I added code similar to the example that I cited. Maybe it was a subclassing/STI issue, I don't remember.
Samo
There were a lot of things when I started rails that didn't work like I thought, so I'd grind away until I found something that did work, and move on. Later I'd come back to find my solution was overkill :) This might be one of those cases. I think it's a bigger possibility in frameworks like this where a lot of "magic" happens behind the scenes.
Jaime Bellmyer