Skip to content

Instantly share code, notes, and snippets.

@thetron
Created February 4, 2014 04:42
Show Gist options
  • Save thetron/8798256 to your computer and use it in GitHub Desktop.
Save thetron/8798256 to your computer and use it in GitHub Desktop.
Multiple polymorphic joins in Rails
# app/models/address.rb
class Address < ActiveRecord::Base
belongs_to :addressable, polymorphic: true
end
# app/models/concerns/addressable.rb
module Addressable
extend ActiveSupport::Concern
module ClassMethods
def has_address(named)
has_one :"#{named}_address", -> { where :address_type => named }, :class_name => "Address", :as => :addressable
define_method "#{named}_address=" do |record|
record.address_type = named
super(record)
end
end
end
end
# app/models/order.rb
class Order < ActiveRecord::Base
include Addressable
has_address :billing
has_address :shipping
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment