Rails Polymorphic has_many

前端 未结 5 1548
眼角桃花
眼角桃花 2020-12-31 07:44

Using Ruby on Rails, how can I achieve a polymorphic has_many relationship where the owner is always of a known but the items in the association will be of some

5条回答
  •  我在风中等你
    2020-12-31 08:31

    I find that polymorphic associations is under documented in Rails. There is a single table inheritance schema, which is what gets the most documentation, but if you are not using single table inheritance, then there is some missing information.

    The belongs_to association can be enabled using the :polymorphic => true option. However, unless you are using single table inheritance, the has_many association does not work, because it would need to know the set of tables that could have a foreign key.

    (From what I found), I think the clean solution is to have a table and model for the base class, and have the foreign key in the base table.

    create_table "products", :force => true do |table|
        table.integer  "derived_product_id"
        table.string   "derived_product_type"
        table.integer  "producer_id"
      end
    
      class Product < ActiveRecord::Base
        belongs_to :producer
      end
    
      class Producer < ActiveRecord::Base
        has_many :products
      end
    

    Then, for a Production object, producer, you should get the products with producer.products.derived_products.

    I have not yet played with has_many through to condense the association to producer.derived_products, so I cannot comment on getting that to work.

提交回复
热议问题