Ruby on rails 如何更新彼此有关系的模型之一?

Ruby on rails 如何更新彼此有关系的模型之一?,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,我尝试用以下步骤更新2个模型 文章 身份证 当前版本 地位 文章历史 身份证 第11条 头衔 内容 版本 这些模型与article_id和current_version=version有关系 首先,我们制作了一张这样的唱片 article.id:1 article.current_version:1 article.status:public article_history.id:1 article_history.title:"test title" article_history.c

我尝试用以下步骤更新2个模型

  • 文章

    • 身份证
    • 当前版本
    • 地位
  • 文章历史

    • 身份证
    • 第11条
    • 头衔
    • 内容
    • 版本
  • 这些模型与article_id和current_version=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来表示。 修改后,文章有多条记录

    请给我一些建议

    class Article
      has_many :article_histories
    
    我们应该做到这一点。如果您需要更多,这里有许多文档:

    如果这不合适,请告诉我们为什么不适合您:)

    抄袭

    # 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!
    
    注意:这段代码只是给你一个如何实现的想法。
    您需要对其进行错误修复,并使其实际运行。

    太好了!稍后让我检查此代码。我会尽快回来的。