使用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>
答案 0 :(得分:1)
状态表的主键是复合的。在检索正确的状态记录时,您需要指定country_id。
a = Shop.find(1)
a.states.where(:country_id => a.country_id)