Sunday, September 6, 2009

Polymorphic Association

Reference : http://charlesmaxwood.com/ruby-on-rails-restful-links-when-you-dont-know-the-class/

Example :

restful routes:

map.resources :users
map.resources :groups

Model Relation:

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

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

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



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 @post.owner.name, polymorphic_path(@post.owner) %>

Documentation : http://railsbrain.com/api/rails-2.3.2/doc/index.html?a=M000261&name=polymorphic_path

Thanks,

Srikanth

No comments: