通过两个不同的模型与同一模型建立多个 has_many 关系,Rails

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

我的 rails 应用程序中有一个模型:

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

显然这段代码不会起作用,因为第二行只会覆盖第一行,但我正在说明我正在努力实现的目标。

其他类:

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

用户应该拥有他们通过自己的网站和供应商上传的图片。

是否有另一种写法,或者我是否需要重新配置现有设置。感谢任何帮助,如果您需要更多信息,请告诉我。

虽然我不太确定你的各种对象之间的关系,但我想我会通过以下方式解决这个问题:

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

那么您应该可以通过访问 @user.site_images@user.supplier_images 来访问用户的图像。

试试这个...(通过使用多态关联,你可以 DRY 它)

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