Phil Brockwell
Phil Brockwell

Reputation: 465

Multiple has_many relationships with same model through two different models, Rails

I have a model in my rails app:

class Image < ActiveRecord::Base
  has_many :users, through: :sites
  has_many :users, through: :suppliers
end

Obviously this code won't work as the second line will just override the first, but I'm illustrating what I'm trying to achieve.

The other classes:

class User < ActiveRecord::Base
  has_and_belongs_to_many :sites, -> { uniq }
end

class Site < ActiveRecord::Base
  has_and_belongs_to_many :users
end

class Supplier < ActiveRecord::Base
  has_and_belongs_to_many :users
  has_and_belongs_to_many :images
end

A user should own images that they've uploaded through sites and suppliers that they own.

Is there another way of writing this or do I need to reconfigure the existing set up. Any help appreciated, let me know if you need more info.

Upvotes: 1

Views: 642

Answers (2)

Mukesh
Mukesh

Reputation: 931

Try this... (By using polymorphic association you can DRY it)

class Image < ActiveRecord::Base
  has_and_belongs_to_many :sites
  has_and_belongs_to_many :suppliers

  has_many :site_users, through: :sites
  has_many :supplier_users, through: :suppliers
end

class User < ActiveRecord::Base
  has_and_belongs_to_many :sites, -> { uniq }
  has_and_belongs_to_many :suppliers
end

class Site < ActiveRecord::Base
  has_and_belongs_to_many :images
  has_and_belongs_to_many :users
end

class Supplier < ActiveRecord::Base
  has_and_belongs_to_many :users
  has_and_belongs_to_many :images
end

Upvotes: 1

nicohvi
nicohvi

Reputation: 2270

Though I'm not quite sure about the relationship between your various objects, I think I'd solve this in the following manner:

class User
  has_and_belongs_to_many :sites
  has_and_belongs_to_many :suppliers

  has_many :site_images, through: :sites
  has_many :supplier_images, through: :suppliers
end

class Site
  has_and_belongs_to_many :users
  has_many :images, as: :imageable
end

class Supplier
  has_and_belongs_to_many :users
  has_many :images, as: :imageable
end

class Image
  belongs_to :imageable, polymorphic: true
end

Then you should be able to access the user's images by accessing @user.site_images and @user.supplier_images.

Upvotes: 1

Related Questions