Ron Avraham
Ron Avraham

Reputation: 478

Rails has_one association through mapping table

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

Upvotes: 0

Views: 233

Answers (1)

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

Upvotes: 1

Related Questions