到目前为止,这是我的代码:
class Video < ActiveRecord::Base
has_paper_trail meta: { athlete_id: :athlete_id, approved: false },
if: Proc.new { |v| v.needs_approval? }
validate :should_be_saved?
def should_be_saved?
errors.add(:base, 'added for approval') if needs_approval?
end
def needs_approval
@needs_approval ||= false
end
def needs_approval?
@needs_approval
end
end
# ApplicationController
class ApplicationController < ActionController::Base
def user_for_paper_trail
return unless user_signed_in?
original_user.present? ? original_user : current_user
end
# Used to determine the contributor
# When contributor logs in, warden saves the contributor_id in session
def original_user
return nil unless remember_contributor_id?
@original_user ||= User.find(remember_contributor_id)
end
def info_for_paper_trail
{ athlete_id: current_user.id } if current_user
end
end
我目前遇到的问题是保存Video对象时验证失败(因为我也告诉过它),但我需要验证失败但版本对象继续创建。只是不太确定如何去做。
EDITS
这是我的代码(下面的代码仍在使用上面的ApplicationController
代码):
class Video < ActiveRecord::Base
# .. other methods
include Contributable
attr_accessible :video_type_id, :athlete_id, :uploader_id, :created_at, :updated_at, :uniform_number, :featured,
:name, :panda_id, :date, :thumbnail_url, :mp4_video_url, :from_mobile_device, :duration, :sport_id,
:delted_at, :approved
end
module Contributable
extend ActiveSupport::Concern
included do
has_paper_trail meta: { athlete_id: :athlete_id, approved: false },
unless: Proc.new { |obj| obj.approved? },
skip: [:approved]
end
def log_changes_or_update(params, contributor = nil)
update_attribute(:approved, false) unless contributor.blank?
if contributor.blank?
update_attributes params
else
self.attributes = params
self.send(:record_update)
self.versions.map(&:save)
end
end
end
class VideosController < ApplicationController
def update
# ... other code
# original_user is the contributor currently logged in
@video.log_changes_or_update(params[:video], original_user)
end
end
我正在处理的应用程序有一小部分复杂性,允许具有特定角色的用户编辑他们也可以访问的配置文件。我试图保存每个更改的版本(使用paper_trail
)而不影响现有对象。
上面的代码完全符合我的要求,但是,我很想知道我的log_changes_or_update
方法是不是正确的方法来实现整体目标。
答案 0 :(得分:2)
为什么不删除验证并将approved
属性的默认值false
添加到Video
模型?这样就保存了Video
对象,并创建了paper_trail version
。稍后当视频获得批准时,paper_trail会注意到这一点也会发生变化。