在编辑前操作 rails 中将数据从一个 table 复制到另一个 table

Copy data from one table to another table in a before edit action rails

我正在构建一个版本控制模型,并正在尝试制作以前版本的副本

Post.rb

  has_many :versions, class_name: "PostVersion",  foreign_key: "post_id", dependent: :destroy

before_update :create_version

private

  def create_version
    PostVersion.create!(title: self.title, body: self.body...[redacted because there is a lot of data...you get the idea])
  end

PostVersion.rb

belongs_to :original_post, class_name: "PostVersion",  foreign_key: "post_id"

在我不列出每一列的情况下,是否有更有效的方法来执行此操作?我正在使用 postgres & Rails 4

如果全部属性标识符相同,而您只是简单地复制过来,请尝试以下操作:

private

  def create_version
    # Modify the keys in except call to filter out additional attrs
    PostVersion.create!(self.attributes.except("id", "created_at", "updated_at"))
  end

或使用paper_trail gem.

其文档中的示例:

class Widget < ActiveRecord::Base
  has_paper_trail
end

widget = Widget.find 153
widget.name                                 # 'Doobly'
widget.versions                             # []
widget.update_attributes :name => 'Wotsit'
widget.versions.last.reify.name             # 'Doobly'
widget.versions.last.event                  # 'update'
widget.versions.last.whodunnit              # '153'  (if the update was via a controller and
                                            #         the controller has a current_user method,
                                            #         here returning the id of the current user)