Created
February 4, 2014 04:42
-
-
Save thetron/8798256 to your computer and use it in GitHub Desktop.
Multiple polymorphic joins in Rails
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/address.rb | |
class Address < ActiveRecord::Base | |
belongs_to :addressable, polymorphic: true | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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