mbleigh / acts-as-taggable-on

A tagging plugin for Rails applications that allows for custom tagging along dynamic contexts.
http://mbleigh.lighthouseapp.com/projects/10116-acts-as-taggable-on
MIT License
4.98k stars 1.19k forks source link

Validate presence of taggings with multiple owners #891

Open vokshirg opened 6 years ago

vokshirg commented 6 years ago

Hi there I have a Companies with acts_as_taggable_on :competences and have Sections with acts_as_tagger Companies categorized with sections through tags, therefore I always need tags 'competences' in Companies.

views/companies/edit

        - @sections.each do |section|
          h4 = t('.competencies', title: section.title)
          = f.text_field "competences_list[#{section.id}]",
                  value: @company.owner_tags_on(section, :competences).each(&:name).join(','),

companies_controller.rb

  def update
    update_competences(params[:company][:competences_list])
    respond_to do |format|
      if @company.update_attributes(company_params)
        flash[:success] = 'Company was successfully update.'
        format.js
      else
        flash[:error] = 'Something went wrong.'
        format.js { render partial: 'common/errors', locals: { resource: @company } }
      end
    end
  end

  def update_competences(competences)
    competences.each {|owner, new_comps| @company.perform_competences(owner, new_comps) }
    params[:company].delete :competences_list
  end

company.rb

acts_as_taggable_on :competences
validates :name, :competences, presence: true

  def add_owned_competences(owner, new_comps)
    competence_owner = Section.find(owner)
    owned_competence_list = [new_comps]
    competence_owner.tag(self, with: owned_competence_list, on: :competences)
  end

  def remove_owned_competences(owner, competences)
    self.competence_list.remove(all_competences_list.reject{ |item| competences.include?(item)})
    if competences.empty?
      section = Section.find(owner)
      section.tag(self, with: '', on: :competences)
    end
  end

  def perform_competences(owner, new_comps)
    self.add_owned_competences(owner, new_comps)
    self.remove_owned_competences(owner,new_comps)
  end

In this case I always geting error "competences cant be blank"

How should i pass competences with any owners (sections) for one company and validate presence at least one competence? Thanks a lot!