Friday, February 19, 2010

rails polymorphic association

You can implement polymorphic associaton among tables COMMENTS, ARTICLES, PHOTOS as follows:
class Comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true

class Article < ActiveRecord::Base
has_many :comments, :as => :commentable

class Photo < ActiveRecord::Base
has_many :comments, :as => :commentable

Then, you need the following statements in order to invoke article with comments:
# in model Article, collect article that has many comments
@article = Article.find(id)
@article_with_comments = @article.comments

Besides, you can also use the following statement to
@article = "articles".classify.constantize.find(id)

No comments:

Post a Comment