class OrgSubfield < ActiveRecord::Base
  belongs_to :organization, :foreign_key => :organization_id
  has_one :subfield_subdomain_dir,:dependent => :destroy
  has_many :org_document_comments, :dependent => :destroy
  has_many :files
  has_many :org_subfield_messages, :dependent => :destroy
  has_many :messages, :through => :org_subfield_messages
  has_many :boards, :dependent => :destroy
  has_many :news, :dependent => :destroy
  has_many :sub_domains, :dependent => :destroy
  acts_as_attachable
  after_create :create_board_sync
  after_destroy :update_priority
  # 创建资源栏目讨论区
  def create_board_sync
    @board = self.boards.build
    #self.name=" #{l(:label_borad_course) }"
    @board.name = " #{l(:label_borad_org_subfield) }"#self.name
    @board.description = self.name.to_s
    @board.project_id = -1
    if @board.save
      logger.debug "[OrgSubfield Model] ===> #{@board.to_json}"
    else
      logger.error "[OrgSubfield Model] ===> Auto create board when org_subfield saved, because #{@board.full_messages}"
    end
  end

  def project
  end

  def update_priority
    OrgSubfield.where("organization_id=? and priority>?", self.organization_id, self.priority).each do |field|
      field.decrement(:priority)
      field.save
    end
  end
end