繁体   English   中英

如何更新具有关联性的模型之一?

[英]How do I update one of model having relation each other?

我尝试通过以下步骤更新2模型。

  1. 文章

    • ID
    • 当前版本
    • 状态
  2. 文章历史

    • ID
    • article_id
    • 标题
    • 内容

这些模型与article_id和current_version =版本有关。

首先,我们创造了这样的记录。

article.id:1
article.current_version:1
article.status:public
article_history.id:1
article_history.title:"test title"
article_history.content:"test content"
article_history.version:1

我将像这样进行更新。 在此之前,我想使用新的ID复制现有的ArticleHistory记录。 我的意思是,这就像更新ArticleHistory。

article.id:1
article.current_version:2
article.status:public
(copied)article_history.id:2
(copied)article_history.title:"updated test title"
(copied)article_history.content:"updated test content"
(copied)article_history.version:2

但是现在,我不知道如何通过RoR ActiveRecord进行表达。 修改后,Article获得了多个记录。

请给我建议。

class Article
  has_many :article_histories

应该可以。 如果您需要更多,则has_many的文档在这里:

http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_many

如果这不合适-请告诉我们为什么它对您不起作用:)

复制...

# first find the article_history with the highest version for this article
latest_history = article.article_histories.order(:version).last
# if there isn't one, create a new one
if latest_history.blank?
  new_history = article.article_histories.new(params[:article_history])
  new_history.version = 1
else
  # Otherwise... merge params and the old attributes
  combined_attributes = latest_history.attributes.merge(params[:article_history])
  # and use that to create the newer article_history version
  new_history = article.article_histories.build(combined_attributes)
  new_history.version = latest_history.version + 1
end
new_history.save!

注意:这段代码只是为了让您了解如何完成此操作。 您将需要对其进行错误修复,并使其真正能够自己工作。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM