Rails版本:5.2.2.1
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
中找到任何内容。
答案 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