2013-10-27 102 views
0

使用Rails 3.2。我有供应商给出的表格,我不能改变。 State有2个外键。下面是简化的代码:has_one关联以匹配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

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

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

但它是'has_one',我必须使用'states'还是改成'has_many'? – Victor

+0

你必须将它改为'has_many',看着你的状态表,你显然有一个商店的多个状态记录。 – rb512