【发布时间】:2015-08-15 11:58:31
【问题描述】:
在 Rails (3.2) 中,在没有名为 belongs_to_many 的关联的情况下,实现 County belongs_to_many Zipcodes 和 Zipcode has_one County 的正确方法是什么?
两个模型都有一个county_code,它在县内是唯一的,并且在邮政编码中标识了该县的所有邮政编码。 (这个例子假设邮政编码从不跨越县)
使用 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 会破坏我没有测试的东西?
【问题讨论】:
标签: ruby activerecord associations