ruby-on-rails - 特定关联模型的 Rails update_attributes

标签 ruby-on-rails activerecord updates accepts-nested-attributes

我有以下设置:

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/

相关文章:

ruby-on-rails - 通过 Rails ActiveRecord Association 调用类方法

ruby-on-rails - 我可以从模型中获取表、列和类型信息吗?

c# - 使用datagridview C#更新数据库中的数据

ruby-on-rails - 将Markdown与Rails结合使用

ruby-on-rails - Rails/Devise---密码重置和重新发送确认如何重定向到主页

ruby-on-rails - 如果不是管理员,用户可以更新自己吗?

rest - 如何使用restful API 实现对象属性更新?

ruby-on-rails - Rails Redis过期方法

c# - 城堡 ActiveRecord "Could not compile the mapping document: (string)"

c# - 通过 TableController 更新 Azure 移动后端表中的记录