簡體   English   中英

rails:has_and_belongs_to_many不保存關聯對象(聯接表中為null)

[英]rails: has_and_belongs_to_many not saving associated objects (null in join table)

Rails 4.我有一個Authentication模型

class Authentication < ActiveRecord::Base
  ...
  has_and_belongs_to_many :posting_groups
  ...
end

PostingGroup模型

class PostingGroup < ActiveRecord::Base
  ...
  has_and_belongs_to_many :authentications
  ...
end

聯接表的遷移如下所示:

def change
  create_table :authentications_posting_groups, id: false do |t|
    t.belongs_to :posting_group
    t.belongs_to :authentication
  end
end

Authentication表和PostingGroup表都不需要互相引用,也不需要引用PostingGroup表,因此它們之間沒有任何相關信息。 更新AuthenticationPostingGroups ,請執行以下操作:

def update
  @authentication.update_attributes(authentication_params)
end
def authentication_params
    params.require(:other_unimportant_stuff, posting_groups: [])
end

在執行update操作期間, params如下:

{“ authentication” => {“ posting_groups” => [“ 17”,“ 18”]},“ stuff” =>“更多內容}

...其中17和18是應保存的發布組的ID。 並且的確, update中的@authentication變量包含所需的PostingGroups並且update_attributes返回true。 但是, Authentication.find(id).posting_groups (即實際存儲在數據庫中的內容)將返回一個空集。 此外,檢查authentications_posting_groups表顯示以下內容:

posting_group_id    authentication_id   
              17    NULL
              18    NULL

出於某些奇怪的原因, authentication_id從未進入數據庫,這很有趣,因為首先是在此對象上觸發了保存。 這不是我第一次遇到此問題,而是第二次,我們第一次注意到在這種情況下創建 Authentication時,一切工作正常(也就是說,那些NULL沒有在數據庫中彈出),但是update也發生了同樣的事情。 在那種情況下,實現了重新創建對象的hack( create一切正常!),但這不是一個選擇。 我非常感謝您提出任何建議,因為這使我們發瘋。 謝謝。

編輯-這是觸發整個事件的表單:

= form_for authentication, remote: true do |f|
  = f.select :posting_groups, options_for_select(@posting_groups.map {|pg| [ pg.name, pg.id ] }), {}, multiple: true, class: "form-control posting_groups_select"

您應該允許posting_group_ids並通過posting_group_ids

調節器

def update
  @authentication.update_attributes(authentication_params)
end
def authentication_params
    params.require(:other_unimportant_stuff, posting_group_ids: [])
end

視圖

= form_for authentication, remote: true do |f|
  = f.select :posting_group_ids, options_for_select(@posting_groups.map {|pg| [ pg.name, pg.id ] }), {}, multiple: true, class: "form-control posting_groups_select"
params.require(:other_unimportant_stuff, posting_group_ids: [])

注意id。

您按照參數傳遞了posting_group_ids ,但是您的參數設置為posting_groups因此強大的參數會過濾掉它。

暫無
暫無

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

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