我正在构建版本控制模型,并且正在尝试制作以前版本的副本
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
答案 0 :(得分:1)
如果所有 属性标识符相同且您只是复制,请尝试以下操作:
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
答案 1 :(得分:0)
或使用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)