has_one关联以匹配2个外键

时间:2013-10-27 06:26:44

标签: ruby-on-rails

使用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>

1 个答案:

答案 0 :(得分:1)

状态表的主键是复合的。在检索正确的状态记录时,您需要指定country_id。

 a = Shop.find(1)
 a.states.where(:country_id => a.country_id)