Vorleak Chy's Blog
Polymorphic Associations in Ruby on Rails
You might have instances where the associations could be with multiple models. For example, if you have a Picture model that can be associated with either a Student model or an Employee model. In this case, you really want to be able to call @picture.imageable to get the image. This is where polymorphic associations come in.
class Picture < ActiveRecord::Base belongs_to :imageable, :polymorphic => true end class Student < ActiveRecord::Base has_many :pictures, :as => :imageable end class Employee < ActiveRecord::Base has_many :pictures, :as => :imageable end
You can think of a polymorphic belongs_to declaration as setting up an interface that any other model can use.
You can also retrieve a collection of pictures: @student.pictures or @employee.pictures from instances of Student or Employee model.
To make this work, you need to declare both a foreign key column and a type column in the model that declares the polymorphic interface:
class CreatePictures < ActiveRecord::Migration
def self.up
create_table :pictures do |t|
t.string :name
t.integer :imageable_id
t.string :imageable_type
t.timestamps
end
end
def self.down
drop_table :pictures
end
end
Finally, you can read more on the documentation written by Rails team.
Subscribe-
Search-
Tags-
Categories-
Recent Comments-
- Using UUID as Primary Key in Ruby on Rails Thanks @Chamnap, I have...
- Using UUID as Primary Key in Ruby on Rails Not working. You need to...
- Installing GeoServer on Ubuntu Thanks for that! You saved me a lot...
- Change background color of TextBox or ComboBox in Windows Forms Hi....
- SQL Server 2005 Update Trigger Effect Multiple Rows Its really helpful...
- Copyright 2010 Vorleak Chy's Blog. All Rights Reserved. Powered by Wordpress | Theme designed by Chris Murphy
- Back To Top
- Home


Leave a Comment-