Skip to content

Instantly share code, notes, and snippets.

@michaelminter
Last active December 22, 2015 07:19
Show Gist options
  • Select an option

  • Save michaelminter/6437384 to your computer and use it in GitHub Desktop.

Select an option

Save michaelminter/6437384 to your computer and use it in GitHub Desktop.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment