has_many :through with class_name and foreign_key

后端 未结 3 2028
迷失自我
迷失自我 2020-12-24 01:06

I\'m working with a fairly straightforward has_many through: situation where I can make the class_name/foreign_key parameters work in one direction but not the other. Perhap

3条回答
  •  轮回少年
    2020-12-24 01:44

    I know this is an old question, but I just spent some time running into the same errors and finally figured it out. This is what I did:

    class User < ActiveRecord::Base
      has_many :listing_managers
      has_many :managed_listings, through: :listing_managers, source: :listing
    end
    
    class Listing < ActiveRecord::Base
      has_many :listing_managers
      has_many :managers, through: :listing_managers, source: :user
    end
    
    class ListingManager < ActiveRecord::Base
      belongs_to :listing
      belongs_to :user
    end
    

    This is what the ListingManager join table looks like:

    create_table :listing_managers do |t|
      t.integer :listing_id
      t.integer :user_id
    end
    

    Hope this helps future searchers.

提交回复
热议问题