使用 Rails 3.2。我有一张供应商提供的表格,我无法更改。有State
2个外键。下面是简化的代码:
# shops.rb
class Shop < ActiveRecord::Base
self.primary_key = "shop_id"
has_one :state, foreign_key: "shop_id"
end
# states.rb
class State < ActiveRecord::Base
self.primary_key = ["shop_id", "country_id"] # when there are multiple parent keys
belongs_to :shops, foreign_key: "shop_id"
end
# shop record
shop_id country_id
====================
1 3
# state records
shop_id country_id
=====================
1 4
1 6
1 3
1 9
您会注意到我只有一条shop
记录shop_id = 1
,但state
会有多条关联记录。如何确保在运行以下命令时返回正确的记录?
a = Shop.find(1)
a.state # => #<State shop_id: 1, country_id: 3>