通过两个不同的模型Rails,使用相同模型的多个has_many关系

时间:2016-06-03 08:38:26

标签: ruby-on-rails ruby ruby-on-rails-3

我的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

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

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

2 个答案:

答案 0 :(得分:1)

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

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来访问用户的图片。

答案 1 :(得分:1)

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

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
相关问题