Rails has_many :through 居然不能识别变形复数

SpiderEvgn · 2020年05月16日 · 最后由 SpiderEvgn 回复于 2020年05月18日 · 3617 次阅读

发现一个很 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 的错误

bar 和 person 是一对一关联?

mizuhashi 回复

关系和官网例子一样,我在原文补齐了

people 单复数同型,person 的复数是 persons

如果是单复数词汇的映射错误,可以添加例外列表到 config/initializers/inflections.rb

加 source 显式指明也不错

看起来是 bug,可以考虑提交 issue 和 pr

ShowLew 回复

可别一概而论,实际上 person 是有两种复数形式的。一般来说,当我们引述相对于“动物”或“东西”的“人”的概念,并为了概括一个不确定数量的群体时,用的是 people;而当引述特定数量范围的独立个体时,用的是 persons。通常 persons 多用于法律法规之类的地方,比如说法院指代犯罪嫌疑人等的时候(因为犯罪嫌疑人的数量总是确定的,你不能给可能存在或不存在的人定罪吧?)就会用 persons。

韦氏词典里有如下阐述,比我说的更专业一些:

Many usage guides over the years have suggested that there is a clear distinction between these two words; people is used when referring to a collective group or indeterminate number, and persons serves better when referring to individuals (or a number of individuals). There are many instances in which this difference may be observed, often when the two words are side by side.

嗯。。。试了几个不同的单词单复数,的确是我搞错了 😂

SpiderEvgn 关闭了讨论。 05月18日 13:43
需要 登录 后方可回复, 如果你还没有账号请 注册新账号