2

我一直在阅读 Rails 协会指南,但我仍然不确定我是否正确执行此操作。

我的应用程序有用户和产品。

用户可以为这些产品提供评论、评论和照片。

我想我会创建一个名为 Contributions 的连接模型:

  belongs_to :user
  belongs_to :building
  belongs_to :contributable, polymorphic: true

然后对于用户:

has_many :contributions, as: contributable
has_many :products, through: contributions

产品:

has_many :contributions, as: contributable
has_many :users, through: contributions

然后例如,在我的 Review 模型中:

belongs_to :user
belongs_to :product

我不觉得我这样做是对的。基本上,我希望贡献始终具有关联的产品和用户,但希望贡献能够包括评论、评论或照片。

具有多态关联的连接表是正确的方法吗?

4

1 回答 1

4

我认为这样的东西是你正在寻找的。

class User < ActiveRecord::Base
  has_many :contributions
end

class Product < ActiveRecord::Base
  has_many :contributions
end

class Contribution < ActiveRecord::Base
  belongs_to :user
  belongs_to :product
  belongs_to :contributable, :polymorphic => true
end

class Comment < ActiveRecord::Base
  has_one :contribution, :as => :contributable
end

class Review < ActiveRecord::Base
  has_one :contribution, :as => :contributable
end

class Photo < ActiveRecord::Base
  has_one :contribution, :as => :contributable
end

确保表中有contributable_idcontributable_type字段contributions

于 2013-05-25T21:40:17.887 回答