Rails4 外部キー名が異なる場合のhas_many through

リレーションで外部キーを変更したあと、has_many throughをしようとして躓いたので、メモ。

UsersテーブルとSalesテーブルとProductsテーブルがあるとする。
UsersテーブルのidとSalesテーブルのcustomer_idを紐づけ、中間テーブルであるSalesを介さずにProductからUserを取得したかった。

class Product < ActiveRecord::Base
  has_many :sales
  has_many :users, :through => :sales
end
class User < ActiveRecord::Base
  has_many :sales, :foreign_key => "customer_id"
end
class Sale < ActiveRecord::Base
  belongs_to :user, :foreign_key => "customer_id"
  belongs_to :product
end

前回rails4 リレーションで外部キー名を変更 - ayaketanのプログラミング勉強日記でSaleには「:foreign_key => "customer_id"」を書いていなかったが、has_many throughを使うときには、必要なようだ。


参考:
ruby on rails - has_many :through with a foreign key? - Stack Overflow