【问题标题】:Rails: polymorphic assoziation, has_many :throughRails:多态关联,has_many :through
【发布时间】:2013-03-11 22:15:26
【问题描述】:

我不确定我是否了解 Rails 多态性。 在 Java 中,您可以从相同的 Objecttype 创建对象: http://www.fh-kl.de/~guenter.biehl/lehrgebiete/java2/j2-08-Dateien/abb.8.10.jpg

 Person trainer = new Trainer()
 Person sportler = new Trainer()

在 Rails 中http://guides.rubyonrails.org/association_basics.html#polymorphic-associations:

在这个例子中:图片可以来自员工或产品,听起来很奇怪,因为这不是同一类型。

我是否了解真正的目的:将对象保存在同一个容器中的人或图像数组?

在我的 Rails 项目中:我有几个人:运动员、教练和客人。他们是人的儿子(继承)。 我想我符合继承的原因。

还有一个类名为练习。

运动员和教练可以创建练习。

所以我想使用多态。练习可以来自教练或运动员。与 rails 页面的示例一样,图像可以来自员工或产品。

我符合最佳实践吗?

如何通过多态实现 has_many :through? 不可能使用与多态的关联。 您必须定义一个额外的类,但具体如何定义?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    我认为您需要单表继承 (STI) 模型,而不是多态关系。

    请参阅这篇文章 http://www.alexreisner.com/code/single-table-inheritance-in-rails 和这些 stackoverflow 答案 Rails - Single Table Inheritance or not for Applicant/Employee relationship Alternative to Rails Single Table Inheritance (STI)?

    【讨论】:

      【解决方案2】:

      为了清楚起见,当您的模型可能属于单个关联上的许多不同模型时,您应该使用多态关联。

      假设,您希望能够为用户和故事编写 cmets。你希望这两个模型都值得称道。这是如何声明的:

      class Comment < ApplicationRecord
        belongs_to :commentable, polymorphic: true
      end
      
      class Employee < ApplicationRecord
        has_many :comment, as: :commentable
      end
      
      class Product < ApplicationRecord
        has_many :comment, as: :commentable
      end
      

      要声明多态接口(值得称赞),您需要在模型中同时声明外键列和类型列。

      class CreateComments < ActiveRecord::Migration
        def change
          create_table :comments do |t|
            t.text :body
            t.integer :commentable_id
            t.string :commentable_type
            t.timestamps
          end
      
          add_index :comments, :commentable_id
        end
      end
      

      您可以查看有关associations here的更多详细信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-12-13
        • 2011-06-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-28
        • 2015-12-17
        相关资源
        最近更新 更多