Search code examples
ruby-on-railsactiverecordupdatesaccepts-nested-attributes

Rails update_attributes for a specific associated model


I have the following setup:

class Post < ApplicationRecord
  has_many :comments, inverse_of: :post, dependent: :destroy
  accepts_nested_attributes_for :comments
end

class Comment < ApplicationRecord
  belongs_to :post
end

If I call post.update_attributes(post_params)

Where post_params is the following:

post_params = {
  "content"=>"Post something",
  "comments_attributes"=>{
    "0"=>{
      "content"=>"comment on something"
    }
  }
}

A comment new comments is created and associated with the post.

Is there a way to us update_attributes on the post and still update a specific comment associated with the post?

Maybe something like:

post_params = {
  "content"=>"Post something",
  "comments_attributes"=>{
    "0"=>{
      "id"=>"1", #if the id exist update that comment, if not then add a new comment.
      "content"=>"comment on something"
    }
  }
}

So then I can call post.update_attributes(post_params) and take advantage of the accepts_nested_attributes_for on updates.

If this is not possible, what is the a best way to do an update of post with an update of an associated comment?

Any Help would be greatly appreciated.


Solution

  • You can update the provided records so long as you maintain the correct model ID for the model.

    So if post has comments with IDs 4,5,6, you can submit:

    post.update(comments_attributes: [{id: 4, content: 'bob'}]
    

    And that will update the existing Comments.find(4) record (provided it validates successfully).

    But if you were to pass an ID that did not apply to the comments that belongs to that post an exception will be thrown.