簡體   English   中英

Rails多對多:通過關聯:在銷毀關聯對象后不會更新關聯對象

[英]Rails many-to-many :through association: associated object is not updated after destroying the association object

由於我是Rails的新手,可能會有一個簡單的解決方案。 但我甚至無法在某個地方找到這個問題。 其他帖子涉及destroy vs. delete(我嘗試了兩個相同的結果)或者只是沒有提到關聯對象的行為方式。

我的問題:我想通過以下方式創建多對多關聯:通過。 當我刪除關聯(即關系對象,而不是相關對象)時,我希望在關聯對象的所有模型實例中刪除(更新)此關聯。 但這並沒有完全發生。

我的例子:

Meeting < ActiveRecord::Base
  has_many :participations
  has_many :users, :through => :participations

User < ActiveRecord::Base
  has_many :participations
  has_many :meetings, :through => :participations

Participation < ActiveRecord::Base
  belongs_to :meeting, :foreign_key => :meeting_id
  belongs_to :user, :foreign_key => :user_id

當我創建新關聯時,相關對象會相應更新:

u = User.find(...)
m = Meeting.find(...)
m.users<< u

以這種方式創建關聯時也是如此:

m.participations.create(:user_id => u.id)  # this requires to make the user_id attribute accessible

當我現在查看關聯的用戶模型實例時,它按預期更新:

u.meetings >> contains the newly created association to the meeting m

當我銷毀(不刪除!)這種關聯時,關聯的對象不會像我期望的那樣更新:

m.users.find_by_user_id(u.id).destroy
m.users >> []
u.meetings >> still contains the destroyed association to meeting m

我原以為u.meetings會更新並為空([])。 添加驗證無助於解決此問題:

Meeting < ActiveRecord::Base
  validates_associated :contacts
or
Participation < ActiveRecord::Base
  validates_presence_of :contact, :interview

我做錯了什么或我在這里錯過了什么?

我正在使用Rails 3.2.8

感謝所有願意幫助我的人。

你應該這樣做:dependent => :destroy

Meeting < ActiveRecord::Base
  has_many :participations, :dependent => :destroy
  has_many :users, :through => :participations

User < ActiveRecord::Base
  has_many :participations, :dependent => :destroy
  has_many :meetings, :through => :participations

Participation < ActiveRecord::Base
  belongs_to :meeting, :foreign_key => :meeting_id
  belongs_to :user, :foreign_key => :user_id

如果相關用戶或會議中的任何一個被銷毀,這將確保破壞participation

您應該使用以下關系選項更新model

dependent: destroy

這將在關聯對象上調用destroy

參考: http//api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#label-Deleting+from+associations

我猜問題可能是這樣的。 在你的例子中,

m.users.find_by_user_id(u.id).destroy
m.users >> []
u.meetings >> still contains the destroyed association to meeting m

uu.meetings已經在m.users.find_by_user_id(u.id).destroy之前加載了。 然后u.meetings輸出緩存的數據。

你可以嘗試u.meetings(true)u.reload; u.meetings u.reload; u.meetings 。看看是否有任何差異。

暫無
暫無

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

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