Create keywords to reference our media
Tag: name: (keyword)
- Generate a model per usual, only reference a "polymorphic association name" (that you'll invent) as the reference model
rails g model Tag name:string taggable:references
- Tell Rails you are using polymorphic associations in your models:
• In the polymorphic model itself, set polymorphic: true on the belongs_to :taggable
class Tag < ActiveRecord::Base
belongs_to :taggable, polymorphic: true
attr_accessible :name
end
• In our migration, we'll also want to set polymorphic: true
class CreateTags < ActiveRecord::Migration
def change
create_table :tags do |t|
t.string :name
t.references :taggable, polymorphic: true
t.timestamps
end
add_index :tags, :taggable_id
end
end
- When we want to use polymorphic models in other models, we simply create the association
class Post < ActiveRecord::Base
# ...
has_many :tags, as: :taggable
# ...
end
• Create tags within your app • Create projects scaffold • Create Pictures/Images polymorphic association and use it with your projects.