【问题标题】:Rails - polymorphic associations with join modelsRails - 与连接模型的多态关联
【发布时间】:2013-05-25 20:57:19
【问题描述】:

我一直在阅读 Rails 协会指南,但我仍然不确定我是否正确地这样做。

我的应用有用户和产品。

用户可以为这些产品贡献 cmets、评论和照片。

我想我会创建一个名为 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

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

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

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

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

    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
    

    确保您的contributions 表中有contributable_idcontributable_type 字段。

    【讨论】:

    • 知道了,谢谢!我需要这种类型的连接表和多态关联吗?我是否也可以只做类似产品 has_many :reviews、has_many :cmets 等的事情,以及对 belongs_to :user 和 belongs_to :product 的评论?
    • 这可能取决于您的应用程序将使用多少这些类型。例如,随着您添加的越来越多,Product 最终可能会比您想要的更多地使用 has_many 宏。要考虑的另一件事是,您是否经常查询所有三种类型的列表。比如你想要一个时间线。您目前可以使用@product.contributions 并根据需要对它们进行排序。否则,您将不得不执行@product.reviews@product.comments@product.photos 并自己手动合并和排序它们。尽管如此,根据您的应用程序,他实际上可能是一件好事。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    • 2011-01-30
    • 2011-05-06
    • 1970-01-01
    • 2011-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多