Two has_many links between the same models

后端 未结 2 1852
太阳男子
太阳男子 2021-01-15 22:52

I have users which have products through a habtm link, which is working.

I want to add a link between the user mod

2条回答
  •  太阳男子
    2021-01-15 23:46

    The :as syntax is for polymorphic associations - this is not what you want. Your comments about your column names are a bit ambiguous, so I'm going to assume that you have a user_id column in your products table which is the id of the creator of that product (I'm only including the relevant associations)...

    class Product < ActiveRecord::Base
      has_and_belongs_to_many :users
      belongs_to :creator, :foreign_key => :user_id, :class_name => "User"
    end
    
    class User < ActiveRecord::Base
      has_and_belongs_to_many :products
      has_many :owned_products, :class_name => "Product"
    end
    

提交回复
热议问题