Rails has_one association through mapping table

233 Views Asked by At

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)?

1

There are 1 best solutions below

0
Int'l Man Of Coding Mystery On
class Apple < ActiveRecord::Base
  has_one :fruit_mapping, as: :fruit
end

class Cart < ActiveRecord::Base
  has_many :fruit_mappigns
  has_many :apples, through: :fruit_mappings, source: :fruit, source_type: 'Apple'
  has_many :bananas, through: :fruit_mappings, source: :fruit, source_type: 'Banana'
end

Using the source and source_type options, you can define the polymorphic relationships. If using source and source_type are depricated in the Rails version you're using you can try

has_many :apples, through: :fruit_mappings, class_name: 'Apple', foreign_key: :fruit_id