2017-03-13 8 views
1

Project、MonthlySubscription(Subscription)、MonthlyTransactionQueue(TransactionQueueのsti)の3つのモデルがあります。サブスクリプションとTransactionQueueの両方belong_toプロジェクト。ActiveRecordを使用した1つのモデルのスナップショット

MonthlySubscriptionのコピーを作成し、Release.released = falseを持つプロジェクトのMonthlyTransactionQueueに配置します。私はARを使ってどのようにこれを行いますか?

私のSQLは次のようになります。ARについては

insert into transaction_queues 
select a.*, b.id as release_id 
from subscriptions a 
left join releases b 
    on a.project_id = b.project_id 
where b.released = false 
and a.type = 'ReleaseSubscription' 

が、私はこのReleaseSubscription.joins(project: :releases)を開始しているが、それはあなたがいくつかのオプションがありますRelease.releasedフィールド

答えて

1

を保持しません

  1. SQLを実行 ReleaseSubscription.connection.execute( "insert into transaction_queues ...")

  2. トランザクション内でARを使用します。

    MonthlyTransactionQueue.transaction do 
    # I'm unsure what Release.released is and how it relates but this should work other than that. 
        MonthlySubscription.where(released: false).each do |sub| 
        MonthlyTransactionQueue.create(sub.attributes) 
    end 
    end 
    

    これにより、複数の挿入文が作成されますが、それらはすべて同じトランザクションで実行されます。

  3. もう1つの良いオプションは、クエリに一致するものすべてをSQLファイルにダンプし、load data in fileを使用してすべてを一度にsqlに追加することです。

+0

ありがとうございます。 'MonthlySubscription.where(リリース:偽)'では、リリースされたフィールドはリリースモデルにあるので、 'MonthlySubscription.joins(Release.where(released:false))'のようなものが必要でしょうか? – Adam12344

+1

'MonthlySubscription.where(released:false).each do | sub |を置き換えます。 ':' MonthlySubscription.joins(:releases).where(リリース:{リリース:偽})。each do | sub | ' – isaacsloan

関連する問題