2017-02-03 5 views
0

2つのモデルを以下の手順で更新しようとしています。お互いに関係のあるモデルを更新するにはどうしたらいいですか?

    • ID
    • CURRENT_VERSION
    • ステータス
  1. ArticleHistory

    • ID
    • タイトル
    • コンテンツ
    • バージョン

これらのモデルはarticle_idにしてCURRENT_VERSION =バージョンと関係を持っているのarticle_id。

まず、このようなレコードを1つ作成しました。

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 

私はこのように更新します。その前に、私は既存のArticleHistoryレコードを新しいIDでコピーしたいと思います。つまり、記事履歴を更新するようなものです。

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で表現する方法を理解できません。 この変更後、記事は複数のレコードを持っています。

私に助言してください。

答えて

0
class Article 
    has_many :article_histories 

はすべきことです。あなたがより多く必要な場合は、has_manyのためのDOCOはここにある:

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! 

注:このコードは、どのように行うことができるかを示すためのものです。 これをバグ修正して、実際に自分自身で動作させる必要があります。

+0

素晴らしい!後でこのコードをチェックしましょう。私はそれがすぐに返されます。 –

関連する問題