简体   繁体   English

如何更新模型对象的关联对象?

[英]How do I update a model object's associated object?

I want to something like the following: 我想要像下面这样的东西:

@user.update_attributes(:name => "Obama", :profile => { :current_location => 'US' })

where User has_one profile. 用户has_one个人资料。

Make them 'nested attributes'. 使它们成为'嵌套属性'。 The documentation says: 文件说:

Consider a Member model that has one Avatar: 考虑具有一个头像的会员模型:

  class Member < ActiveRecord::Base
    has_one :avatar
    accepts_nested_attributes_for :avatar
  end

... ...

allows you to update the avatar through the member: 允许您通过成员更新头像:

  params = { :member' => { :avatar_attributes => { :id => '2', :icon => 'sad' } } }
  member.update_attributes params['member']
  member.avatar.icon # => 'sad'

As bjelli has stated it's the accepts_nested_attributes_for method that you probably want here. 正如bjelli所说,这是你可能想要的accepts_nested_attributes_for方法。 It's important to notice that it is the passing in of the profile's :id attribute that allows it to recognize it's an update you want to peform. 重要的是要注意它是传递profile的:id属性,它允许它识别它是你要执行的更新。

I would recommend reading this the nested_attributes.rb comments to understand more : ) 我建议阅读这个nested_attributes.rb注释以了解更多:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Rails更新关联模型的对象 - Rails update associated model's object 如何保存关联对象的计数器? - How do I update a counter of an associated object before it is saved? 在创建/更新之前如何更新模型对象? - How do I update my model object before a create/update? 我如何使用ActiveRecord通过中介模型对象有条件地获取一些模型的对象及其关联的模型的对象 - How can I get some model's objects and its associated model's objects conditionally through an intermediary model object, using ActiveRecord 关联模型的表单对象中的NoMethodError - NoMethodError in Associated model's form object 如何在Rails / Active Record中保存关联的对象 - How do i save an associated Object in Rails / Active Record 如何优雅地检查对象和关联对象的存在? - How do I elegantly check for presence of both the object and associated objects? 如何访问关联模型的关联模型? - How do I access an associated model of an associated model? 使用ajax和rails删除和更新关联模型的对象 - delete and update a object of associated model using ajax and rails 如果具有相同属性的旧 object 关联到同一个当前对象的关联表,则不要创建 object - Do not create object if old object with same attribute is associated to same current object's associated table
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM