Can a model belong_to more than one model?
class Comment < Acti开发者_C百科veRecord::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
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.
精彩评论