has_one 和 has_many 等同于 ActiveRecord 中的 has_one 和 belongs_to_many 吗?

is has_one and has_many equivalent to has_one and belongs_to_many in ActiveRecord?

在 Rails (3.2) 中,什么是实现县 belongs_to_many 邮政编码和邮政编码 has_one 县的等效方法的正确方法,假设没有名为 [=31 的关联=] ?

两种型号都有一个 county_code,它在县内是唯一的,并且在 Zipcode 中标识该县的所有邮政编码。 (此示例假设邮政编码从不跨越县)

使用 has_one 和 belongs_to 不提供访问县内所有邮政编码的方法:

class Zipcode < ActiveRecord::Base
  has_one :county, foreign_key: "county_code", primary_key: "county_code"
end

class County < ActiveRecord::Base
     # belongs_to_many would be correct, if such a thing existed
  belongs_to :zipcode, foreign_key: "county_code", primary_key: "county_code"
end

# not defined because of the belongs_to
all_zipcodes_in_in_1st_county = County.first.zipcodes

另一方面,使用 has_one 加 has_many 似乎 可以达到目的:

class Zipcode < ActiveRecord::Base
  has_one :county, foreign_key: "county_code", primary_key: "county_code"
end

class County < ActiveRecord::Base
  has_many :zipcodes, foreign_key: "county_code", primary_key: "county_code"
end

是否遗漏了某种形式的 belongs_to 破坏了我没有测试的东西?

通常您会使用 belongs_to 而不是 has_one 来建立反向关系(例如 Zipcode 会使用 belongs_to 而不是 has_one)。两者的区别在于belongs_to表示底层table有一个指向另一个table的外键字段,其中has_one表示它是相关的table具有指向当前 table.

的外键

因为你有 county_code 作为两个 table 的字段(因此必须明确声明哪些字段将用作 FK 和 PK)你可以有效地使用 has_onebelongs_to 可互换,更多的是感觉语义正确的问题。