2

I can't figure out how to make this work; I've looked at other SO questions including this one and this one but to no avail.

Here are my models:

class User < ActiveRecord::Base
  has_many :connections
  has_many :data_sources, through: :connections
end

class Connection < ActiveRecord::Base
  belongs_to :user
  belongs_to :data_source
end

class DataSource < ActiveRecord::Base
  has_many :connections
  has_many :users, through: :connections
end

class AdNetwork < DataSource
end

class Marketplace < DataSource
end

AdNetwork, Marketplace and DataSource all use the same table through STI.

I want to set up associations on User called marketplaces and ad_networks which return all the data_sources where type is MarketPlace or AdNetwork respectively. How can I do this?


Things I've tried that didn't work:

class User
  has_many :marketplaces, through: :data_sources # Throws an error
  has_many :marketplaces, through: :connections # Throws an error
  has_many :marketplaces, through: :connections, source: :data_source # Returns ALL data sources, not just Marketplaces
  has_many :marketplaces, { through: :connections, source: :data_source }, -> { where(type: "Marketplace" } # Again this returns ALL data sources. Wtf???
end

I also tried adding a column data_source_type to Connection and adding the following lines

class Connection belongs_to :data_source, polymorphic: true
end

class DataSource has_many :connections, as: :data_source end

class User has_many :marketplaces, through: :connections, source: :data_source, source_type: "Marketplace" end

... but now #marketplaces returns an empty relation. (It looks like data_source_type is ALWAYS being set to DataSource, even when I add a Marketplace or an AdNetwork.)

What am I doing wrong?

Community
  • 1
  • 1
GMA
  • 5,816
  • 6
  • 51
  • 80

0 Answers0