# == Schema Information
#
# Table name: clas
#
#  id              :integer          not null, primary key
#  name            :string(255)      not null
#  key             :string(255)      not null
#  content         :text(65535)
#  organization_id :integer          not null
#  pr_need         :boolean          default("0")
#  count           :integer          default("0")
#  created_at      :datetime         not null
#  updated_at      :datetime         not null
#
# Indexes
#
#  index_clas_on_key              (key)
#  index_clas_on_organization_id  (organization_id)
#

class Cla < ApplicationRecord
    has_many :user_clas, :dependent => :destroy
    has_many :users, through: :user_clas
    belongs_to :organization
    
    def to_param
        self.key.parameterize
    end

    def self.build(params,org_id)
        self.create!(organization_id: org_id,
                    name: params[:name],
                    key: params[:key], 
                    content: params[:content],
                    pr_need: params[:pr_need]
                )
    end

    def valid_sign(user_id)
        user_clas.where(user_id: user_id, state:1).present?
    end
    def fresh_count
        number = self.user_clas.where(state: 1).count
        update(count: number)
    end
end
