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
end

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

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

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