Skip to content

Instantly share code, notes, and snippets.

@brycesenz
Created November 11, 2016 19:09
Show Gist options
  • Save brycesenz/2a879f6cbcb42c7d391c8d68a81afdec to your computer and use it in GitHub Desktop.
Save brycesenz/2a879f6cbcb42c7d391c8d68a81afdec to your computer and use it in GitHub Desktop.
Failing has_one through association
class Listing < ActiveRecord::Base
belongs_to :owner, polymorphic: true
belongs_to :property, polymorphic: true
validates :active, inclusion: { in: [true, false] }
end
class Car < ActiveRecord::Base
has_many :listings, as: :property, inverse_of: :property
end
class Boat < ActiveRecord::Base
has_many :listings, as: :property, inverse_of: :property
end
class House < ActiveRecord::Base
has_many :listings, as: :property, inverse_of: :property
end
class Person < ActiveRecord::Base
has_many :listings, as: :owner, inverse_of: :owner
has_many :cars, through: :listings, source: :property, source_type: 'Car'
has_many :boats, through: :listings, source: :property, source_type: 'Boat'
has_many :houses, through: :listings, source: :property, source_type: 'House'
has_many :active_listings, -> { where active: true }, as: :owner, inverse_of: :owner
# This fails
has_one :active_car, through: :active_listings, source: :property, source_type: 'Car'
# ActiveRecord::HasOneThroughCantAssociateThroughCollection:
# Cannot have a has_one :through association 'Person#active_card' where the :through association
# 'Person#active_listings' is a collection.
# Specify a has_one or belongs_to association in the :through option instead.
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment