Ruby on rails 多态关联中需要多对一关系

Ruby on rails 多态关联中需要多对一关系,ruby-on-rails,ruby,activerecord,polymorphic-associations,Ruby On Rails,Ruby,Activerecord,Polymorphic Associations,我有三种型号 class User < ActiveRecord::Base has_one :image, :as => :imageable, :dependent => :destroy end class Product < ActiveRecord::Base has_one :image, :as => :imageable, :dependent => :destroy end class Image < ActiveR

我有三种型号

class User < ActiveRecord::Base
    has_one :image, :as => :imageable, :dependent => :destroy
end

class Product < ActiveRecord::Base
    has_one :image, :as => :imageable, :dependent => :destroy
end

class Image < ActiveRecord::Base
    belongs_to :imageable, polymorphic: true
end
要求对多个产品具有相同的图像。i、 许多产品都有一个形象

p1、p2、p3->img1


没有额外的桌子,有没有办法做到这一点。请帮忙。

这可能不是您想要的,但它会满足您的要求,可能是最简单的解决方案

class User < ActiveRecord::Base
    belongs_to :image
end

class Product < ActiveRecord::Base
    belongs_to :image
end

class Image < ActiveRecord::Base
    has_many :users
    has_many :products

    def imageables
        return users + products
    end
end

你想用什么来处理这个案子,一些代码?怎么了?你指的是哪一张额外的表格?一张图片会属于多个用户吗?一张图片是否同时属于用户和产品?我认为两个都不行,但你应该澄清一下。乔卡尔霍恩,两个都不行。我只需要产品。嗨,Monk_代码,现在images table的字段:imageable_type和imageable_id正在存储用户/产品和用户/产品id。如果我创建一个额外的表,我可以将imageable_type和imageable_id存储为新表名和id。新表字段中有media_id和product_id。但我希望在没有新表的情况下实现这一点。