我有以下设置:
class Post < ApplicationRecord
has_many :comments, inverse_of: :post, dependent: :destroy
accepts_nested_attributes_for :comments
end
class Comment < ApplicationRecord
belongs_to :post
end
如果我调用post.update_attributes(post_params)
其中 post_params
如下:
post_params = {
"content"=>"Post something",
"comments_attributes"=>{
"0"=>{
"content"=>"comment on something"
}
}
}
创建一条新评论并将其与该帖子关联。
有没有办法让我们更新帖子的属性并仍然更新与帖子相关的特定评论?
也许是这样的:
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"
}
}
}
这样我就可以调用 post.update_attributes(post_params)
并利用更新时的 accepts_nested_attributes_for
。
如果这是不可能的,那么通过更新相关评论来更新帖子的最佳方法是什么?
任何帮助将不胜感激。
最佳答案
只要维护模型的正确模型 ID,您就可以更新提供的记录。
因此,如果post
有ID为4、5、6的comments
,您可以提交:
post.update(comments_attributes: [{id: 4, content: 'bob'}]
这将更新现有的 Comments.find(4)
记录(前提是验证成功)。
但是,如果您传递的 ID 不适用于属于该帖子的评论,则会引发异常。
关于ruby-on-rails - 特定关联模型的 Rails update_attributes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42404629/