簡體   English   中英

has_many與兩個外鍵的關系

[英]has_many relation with two foreign keys

在我的應用程序中,一個城市可以有很多鏈接。 鏈接將兩個城市連接在一起並且是雙向的,因此鏈接沒有“從”和“到”。 這導致以下db schema

  create_table "links", force: true do |t|
    t.integer "endpoint1_id"
    t.integer "endpoint2_id"
    t.integer "capacity"
  end

  create_table "cities", force: true do |t|
    t.string "name"
    t.string "lat"
    t.string "long"
  end

在我的ActiveRecord模型中,我想聲明兩個表之間的關系。 因為我在設置has_many關系時似乎無法聲明兩個外鍵,所以II解決了這個問題:

class City < ActiveRecord::Base    
  # has_many with two foreign keys?
  # has_many :links
  def links
    Link.where("endpoint1_id=? OR links.endpoint2_id=?", id, id)
  end    
end

class Link < ActiveRecord::Base
  belongs_to :endpoint1, :class_name => 'City'
  belongs_to :endpoint2, :class_name => 'City'
end

這允許我這樣做: City.find(1).links但似乎不是一個合適的解決方案,並且不強制執行任何繼承。 此外,從link我找不到關系城市,除非我通過city.endpoint1city.endpoint2

是否有更優雅的解決方案來定義與兩個外鍵的has_many關系? 或者我是否可以放棄這種方法並以某種方式更改我的db schema

我認為這與在類似Facebook的應用程序中的“友誼”一樣,其中一個用戶跟隨另一個用戶,並且他們都互相關注,他們是朋友。 我之前有過這個,我通過加入友誼表來解決它,這將給予所有相互的友誼。 這里的不同之處在於,無論方向如何,連接始終存在,但總的來說,我看到了之前遇到的同樣問題。 我的建議是:

  1. 創建鏈接時,始終始終創建它們,Link.new(endpoint1_id:city_1_id,endpoint2_id:city_2_id)Link.new(endpoint2_id:city_1_id,endpoint1_id:city_2_id)

  2. 然后在從一個城市的連接中搜索時,從城市和鏈接中選擇一個sql語句,如下所示:

     def connections # find your cities, where connections run both ways City.find_by_sql " select * from cities where id in (select f2.endpoint1_id from links as f1 inner join links as f2 on (f1.endpoint1_id = f2.endpoint2_id) and (f1.endpoint2_id = f2.endpoint1_id) and (f1.endpoint1_id = #{id.to_i}))" # normally this can cause an sql injection, but here it is handled by to_i end 

此解決方案可能不是此問題的最佳解決方案,但它肯定更靈活,因為它還允許您以相同的方式處理單向連接。

暫無
暫無

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

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