【问题标题】:How do I update one of model having relation each other?如何更新具有相互关系的模型之一?
【发布时间】:2017-02-03 03:15:43
【问题描述】:

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

  1. 文章

    • 身份证
    • 当前版本
    • 状态
  2. 文章历史

    • 身份证
    • article_id
    • 标题
    • 内容
    • 版本

这些模型与 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 来表达。 修改后,Article 有多个记录。

请给我建议。

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:
    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!
    

    注意:这段代码只是为了让您了解它是如何完成的。 你需要修复它并让它自己真正工作。

    【讨论】:

    • 太棒了!让我稍后检查此代码。我会尽快回来。
    猜你喜欢
    • 2015-09-02
    • 2020-04-18
    • 2023-01-31
    • 1970-01-01
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 2012-08-27
    • 1970-01-01
    相关资源
    最近更新 更多