2
這裏是我到目前爲止的代碼:在Rails中使用PaperTrail批准/拒絕編輯
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
我遇到現在的問題是,當視頻對象保存在驗證失敗(因爲我告訴它太) ,但我需要驗證失敗,但版本對象繼續創建。只是不太確定如何去做這件事。
編輯
這裏是我的代碼(下面的代碼仍然使用從上面的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
方法中是否不是完成總體目標的正確方法。
感謝您的幫助!這正是我最終做的!謝謝! – dennismonsewicz
很高興你的工作! – jcm
我更新了我的問題,以包含我正在使用的一些新代碼。思考? – dennismonsewicz