簡體   English   中英

在Rails中使用復合鍵更新模型嵌套屬性

[英]Update model nested attributes with composite key in rails

我有一個具有one_to_many關系的模型:

class Work < ActiveRecord::Base
   has_many :work_right_holders
   accepts_nested_attributes_for :work_right_holders, allow_destroy: true
end

class WorkRightHolder < ActiveRecord::Base
  self.primary_keys = :work_id, :right_holder_id, :role

  belongs_to :work
  belongs_to :right_holder
end

當我嘗試使用嵌套屬性更新work時,它會在關系中創建對象的新實例,而不是根據其主鍵更新現有對象:

work.update(
  {"work_right_holders_attributes"=>
    {
     "0"=>{ "role"=>"Author", 
            "right_holder_id"=>"2", 
            "work_id"=>work.id, 
            "share"=>"11"
           }
     }
  }
)

為什么會這樣呢?

您需要傳遞收集對象ID,如下所示:

work.update(
  {"work_right_holders_attributes"=>
    {
     "0"=>{ "role"=>"Author", 
            "right_holder_id"=>"2", 
            "work_id"=>work.id, 
            "share"=>"11",
            "id" => [work.id, "2", "Author"]
           }
     }
  }
)

這應該工作。

obs:在Rails 4.1.1中有一個錯誤,該錯誤不起作用,但是在Rails 4.2.1中,它正在起作用

暫無
暫無

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

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