在Rails中使用复合键更新模型嵌套属性 [英] Update model nested attributes with composite key in rails

查看:74
本文介绍了在Rails中使用复合键更新模型嵌套属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模型与one_to_many相关:

I have a model with one_to_many relatioship:

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时,它会在关系中创建对象的新实例,而不是根据其主键更新现有对象:

When I try to update a work with nested attributes, it create new instances of object in the relationship, instead of updating the existing based on their primary key:

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

为什么会这样?

推荐答案

您需要传递收集对象ID,如下所示:

You need to pass the collection object id, like this:

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中它起作用了

这篇关于在Rails中使用复合键更新模型嵌套属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆