Sunday, September 6, 2009

Polymorphic Association

Reference :

Example :

restful routes:

map.resources :users
map.resources :groups

Model Relation:

class Post < ActiveRecord::Base
belongs_to :owner, :polymorphic => true

class User < ActiveRecord::Base
has_many :posts, :as => :owner

class Group
has_many :posts, :as => :owner

Now, let’s say that when you show a post, you want to provide a link to the owner of the post when you display it on its show page. You know that because you’ve provided the restful routes in your config/routes.rb file as show above, you get the nice functionality of the user_path and the group_path methods. The problem is that because you don’t know if @post.owner is a user or a group.

<%= link_to, polymorphic_path(@post.owner) %>

Documentation :



No comments: