为什么在用Rails保存副本数据时`after_save`不起作用?

时间:2019-05-20 05:26:16

标签: ruby-on-rails

Rails版本:5.2.2.1

DB

db / migrate / 20190520050333_create_posts.rb

class CreatePosts < ActiveRecord::Migration[5.2]
  def change
    create_table :posts do |t|
      t.string :title
      t.text :body

      t.timestamps
    end
  end
end

db / migrate / 20190520050350_create_post_copies.rb

class CreatePostCopies < ActiveRecord::Migration[5.2]
  def change
    create_table :post_copies do |t|
      t.string :title
      t.text :body

      t.timestamps
    end
  end
end

型号

app / models / post.rb

class Post < ApplicationRecord
  after_save :save_post_copy

  private

  def save_post_copy
    if title_changed?
      post_copy = PostCopy.new
      post_copy.id = self.id
      post_copy.title = self.title
      post_copy.body = self.body
      post_copy.save!
    end
  end
end

控制台

post = Post.first
post.title = 'change title'
post.title_changed? # => true
post.save!

PostCopy.first
=> nil

post_copies中更改title时,这里要自动将记录保存到posts。但是将记录保存在posts中之后,就无法在post_copies中找到任何内容。

1 个答案:

答案 0 :(得分:1)

可能id不应显式设置,因为导轨会自动分配id的值

  def save_post_copy
    if self.title_changed?
      post_copy = PostCopy.new
      #post_copy.id = self.id
      post_copy.title = self.title
      post_copy.body = self.body
      post_copy.save!
    end
  end

或者

  after_save :save_post_copy, if: : saved_change_to_title

  def save_post_copy
    post_copy = PostCopy.new
    post_copy = self.dup
    post_copy.save
  end