require 'elasticsearch/model' class Need < ActiveRecord::Base include Workflow scope :shared, -> { where(state: ["verified", "negociating", "negociated", "failed"]) } scope :with_wishes_count, -> { joins('left join wishes on wishes.need_id = needs.id') .select('needs.*, count(wishes.id) as wishes_count') .group("needs.id") } scope :with_messages_count, -> { joins('left join messages on messages.need_id = needs.id') .select('needs.*, count(messages.id) as messages_count') .group("needs.id") } scope :search, -> (search) { where('title LIKE ?', "%#{search}%") } workflow_column :state acts_as_paranoid has_many :wishes, dependent: :destroy has_many :customers, -> { uniq }, through: :wishes has_many :messages, dependent: :destroy belongs_to :category, class_name: "NeedCategory" validates :title, :presence => true, length: {within: 4..128} validates :description, presence: true, length: {maximum: 65535} belongs_to :author, class_name: 'Customer' # Need's workflow lifecycle workflow do state :created do event :validate, :transitions_to => :verified event :refuse, :transitions_to => :refused end state :refused state :verified do event :negociate, :transitions_to => :negociating end state :negociating do event :accept, :transitions_to => :negociated event :reject, :transitions_to => :failed end state :negociated state :failed end # Human state conversion def human_state case state when 'created' "En attente de validation" when 'verified' "Pas encore négocié" when 'refused' "Refusé" when 'negociating' "En cours de negociation" when 'negociated' "Négociation effecutée" when 'failed' "Négociation échouée" else "Inconnu" end end def categories collection = [] parent_category = self.category if(parent_category) collection << parent_category parent_category.ancestors.each do |c| collection << c end end collection end def category_path if !@category_path @category_path = self.categories.map { |c| c.name }.reverse.join(' \ ') end @category_path end end