3

これまでの私のコードは次のとおりです。

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方法が全体的な目標を達成するための正しい方法ではないかどうかを知りたいだけです.

4

1 に答える 1