michaelminter
9/4/2013 - 2:04 PM

Create Active Record associations automatically with polymorphic database models http://api.rubyonrails.org/classes/ActiveRecord/Associat

Create Active Record associations automatically with polymorphic database models

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Auto-generated+methods

class Picture < ActiveRecord::Base
  belongs_to :imageable, :polymorphic => true
  attr_accessible :imageable_id, :imageable_type, :name, :url
end

class Document < ActiveRecord::Base
  has_many :pictures, :as => :imageable
  attr_accessible :title, :content
end

class User < ActiveRecord::Base
  has_many :pictures, :as => :imageable
  attr_accessible :name, :email, :superpower
end

@document = Document.new({ :title => 'New Document', :content => 'Lorem ipsum' })

# download file, save reponse as @photo

@document.build_picture({ :name => 'Kitty', :url => @photo.path })

@document.save