Given these 4 Rails models:
class Apple < ActiveRecord::Base
has_one: ?
end
class Banana < ActiveRecord::Base
has_one: ?
end
class FruitMapping < ActiveRecord::Base
belongs_to :fruit, polymorphic: true
has_one :cart
end
class Cart < ActiveRecord::Base
end
How can I connect the has_one of the Apple/Banana to Cart, so that when I write apple.cart I will get the relevant Cart (through the mappings table)?
Using the
sourceandsource_typeoptions, you can define the polymorphic relationships. If usingsourceandsource_typeare depricated in the Rails version you're using you can tryhas_many :apples, through: :fruit_mappings, class_name: 'Apple', foreign_key: :fruit_id