发现一个很 2b 的问题。
Rails 官网给 has_many :through
举的例子如下:
class Physician < ApplicationRecord
has_many :appointments
has_many :patients, through: :appointments
end
class Appointment < ApplicationRecord
belongs_to :physician
belongs_to :patient
end
class Patient < ApplicationRecord
has_many :appointments
has_many :physicians, through: :appointments
end
如果把 model 名字改成单复数需要变形的单词就报错了,必须加上 source 指明 model 原单数名称,比如:
class Person < ApplicationRecord
has_many :bars
has_many :foos, through: :bars
end
class Bar < ApplicationRecord
belongs_to :person
belongs_to :foo
end
class Foo < ApplicationRecord
has_many :bars
has_many :people, through: :bars, source: 'person'
end
如果不加这个 source: 'person'
,在查询 @foo.people
时就会报 ActiveRecord::HasManyThroughSourceAssociationNotFoundError
的错误