2014-01-21 21 views
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方法中是否不是完成總體目標的正確方法。

回答

2

爲什麼不只是刪除驗證並將approved屬性的默認值爲false添加到Video模型?這樣保存了Video對象並創建了paper_trail version。稍後當視頻獲得批准時,paper_trail也會注意到此更改。

+0

感謝您的幫助!這正是我最終做的!謝謝! – dennismonsewicz

+0

很高興你的工作! – jcm

+0

我更新了我的問題,以包含我正在使用的一些新代碼。思考? – dennismonsewicz

相關問題