簡體   English   中英

Rails關聯多字符串外鍵

[英]Rails associations multiple string foreign key

我似乎無法弄清楚如何為外鍵匹配多個字符串列。 我有兩個模型。 商店和鄰里。 兩者都有“城市”和“州”列。

如何與多個外鍵字符串建立關聯? 目前,不列顛哥倫比亞省溫哥華附近將展示不列顛哥倫比亞省溫哥華和華盛頓州溫哥華的商店。

Shop
- ID
- City (String)
- State (string)
- Country (string)

belongs_to :neighborhood, foreign_key: :city, primary_key: :city

Neighborhood
- ID
- City (String)
- State (String)
- Country (String)

has_many :shops, foreign_key: :city, primary_key: :city

休息一下,想出了一個簡單的解決方案。

店鋪型號:

belongs_to :neighborhood, foreign_key: :city, primary_key: :city

def neighborhood
  Neighborhood.find_by_city_and_state(city, state)
end

鄰居模型:

has_many :shops, foreign_key: :city, primary_key: :city 

def shops
  Shop.where(city: city, state: state)
end

您的模式可以改善。

您用字符串引用了一個“ foreign_key ” ...它應該是一個integer 如果您重構模式,問題將完全消失。

#app/models/shop.rb
class Shop < ActiveRecord::Base
   # id | city_id | ...
   belongs_to :city
end

#app/models/city.rb
class City < ActiveRecord::Base
   has_many :shops
   belongs_to :state #-> can be removed
end

#app/models/state.rb
class State < ActiveRecord::Base
   belongs_to :country #-> can be removed
end

從本質foreign_keyforeign_key必須標識關聯表的primary_keyunique_key ):

在關系數據庫的上下文中,外鍵是一個表中的一個字段(或字段的集合),它唯一地標識另一個表的一行

這意味着,如果您引用的是城市 ,則城市的“名稱”是否相同都無關緊要...如果另一個表中包含適當的數據(例如,一個CityState內的唯一位置等)。

-

我建議您重構模型,以便Shop belongs_to City 然后,您可以將每個City與各自的states等相關聯。

除了使用“ StateCountry模型之外,您還可以使用“ countries gem,其中包括對世界上各個國家/地區及其州的引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM