Sha256: c3aec7e30f59d8912b53ee80b9d9bf9ec07ee6bc5f94ec19f912a351d10e1fd5

Contents?: true

Size: 1.78 KB

Versions: 3

Compression:

Stored size: 1.78 KB

Contents

class Project < ActiveRecord::Base
  belongs_to :user
  belongs_to :organization
  
  has_many :project_users, dependent: :destroy
  has_many :comments, as: :commentable, dependent: :destroy
  
  has_and_belongs_to_many :users
  has_and_belongs_to_many :areas
  
  scope :for_product_id, ->(product_id) do
    product_id = product_id.to_s
    product_id = product_id == 'no-name' ? '' : product_id
    where(product_id: product_id)
  end
  
  accepts_nested_attributes_for :areas, allow_destroy: true
  
  validates :user_id, presence: true
  validates :name, presence: true, uniqueness: true
  validates :text, presence: true
  validates :area_ids, presence: true
  
  attr_accessible :organization_id, :product_id, :name, :text, :url, :area_ids
  
  extend FriendlyId
  
  before_validation :include_areas_of_product
  after_create :create_project_user
  after_destroy :destroy_non_active_records
  
  friendly_id :name, use: :slugged
  
  PARENT_TYPES = ['area', 'product', 'user', 'organization']
  
  # belongs_to (Mongo DB)
  def product
    return @product if @product
    
    @product = product_id.blank? ? nil : Product.find(product_id)
  end
  
  def product=(document)
    @product = document
    self.product_id = @product.try(:id)
  end
    
  # has_many (Mongo DB)
  def story_class
    if product_id.present?
      "#{product.class.name}::Story".constantize rescue Story
    else
      Story
    end
  end
   
  def stories; story_class.where(project_id: id); end
  
  private
  
  def include_areas_of_product
    self.area_ids ||= []
    
    if product
      self.area_ids += product.areas.map(&:id)
      self.area_ids.uniq!
    end
  end
  
  def create_project_user
    ProjectUser.create(project_id: id, user_id: user_id)
  end
  
  def destroy_non_active_records
    stories.destroy_all
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
voluntary-0.5.2 app/models/project.rb
voluntary-0.5.1 app/models/project.rb
voluntary-0.5.0 app/models/project.rb