多态关联状态受到关注

时间:2014-02-18 18:13:40

标签: ruby-on-rails ruby-on-rails-4

我创造了关注,其中放置了关联。

我需要建立多态关联状态。

has_one :status, class_name: 'VideoStatus', inverse_of: :video, dependent: :destroy

belongs_to :video, inverse_of: :status

我不能成为那个协会。如何成功?

require 'active_support/concern'

module EncodeStatuses
  extend ActiveSupport::Concern

  FORMATS  = %w[mp4]

  HIGH_VERSION   = 'high'
  MEDIUM_VERSION = 'medium'
  LOW_VERSION    = 'low'

  VERSIONS = [HIGH_VERSION, MEDIUM_VERSION, LOW_VERSION]

  included do
    has_one :status, class_name: 'VideoStatus', inverse_of: :video, dependent: :destroy
    accepts_nested_attributes_for :status, update_only: true
    delegate :success?, :failure?, :waiting?, :encoding?, to: :status
  end
end

模型/ video.rb

class Video < ActiveRecord::Base
  include EncodeStatuses
  ...
end

模型/ post.rb

class Post < ActiveRecord::Base
  include EncodeStatuses
  ...
end

模型/ video_status.rb

class VideoStatus < ActiveRecord::Base
  STATUS_WAITING  = 'waiting'
  STATUS_ENCODING = 'encoding'
  STATUS_SUCCESS  = 'success'
  STATUS_FAILURE  = 'failure'

  STATUSES = [STATUS_WAITING, STATUS_ENCODING, STATUS_SUCCESS, STATUS_FAILURE]

  belongs_to :video, inverse_of: :status
  belongs_to :post, inverse_of: :status
  ...
end

1 个答案:

答案 0 :(得分:0)

has_one :status, as: :video_status, dependent: :destroy

class VideoStatus < ActiveRecord::Base
  belongs_to :video_status, polymorphic: true
end