到目前为止,这是我的代码:
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 对象时验证失败(因为我也告诉过它),但我需要验证失败,但版本对象继续创建。只是不太确定如何去做。
编辑
这是我的代码(下面的代码仍然使用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
方法中是否不是实现总体目标的正确方法。