0

使用 Rails 3.2。我有一张供应商提供的表格,我无法更改。有State2个外键。下面是简化的代码:

# 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>
4

1 回答 1

1

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

 a = Shop.find(1)
 a.states.where(:country_id => a.country_id)
于 2013-10-27T06:34:30.360 回答