【问题标题】:Update model nested attributes with composite key in rails使用rails中的复合键更新模型嵌套属性
【发布时间】:2015-08-20 20:56:35
【问题描述】:

我有一个具有 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"
           }
     }
  }
)

为什么会这样?

【问题讨论】:

  • 你现在更新的怎么样了?我以这种方式向您展示的语法?

标签: ruby-on-rails activerecord nested-attributes composite-key composite-primary-key


【解决方案1】:

你需要传递集合对象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 中它可以工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-08-16
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多