Update owner tags via form

前端 未结 7 1835
Happy的楠姐
Happy的楠姐 2020-12-18 01:26

I would like to uniquely use owner tags in my app. My problem is that when I create / update a post via a form I only have f.text_field :tag_list which only upd

7条回答
  •  悲哀的现实
    2020-12-18 02:05

    Late to the party, but I found guillaume06's solution worked well, and I added some additional functionality to it:

    What this will enable: You will be able to specify the tag owner by the name of the relationship between the tagged model and the tag owner model.

    How: write a module and include in your lib on initialization (require 'lib/path/to/tagger'):

      module Giga::Tagger
        extend ActiveSupport::Concern
        included do
          def self.tagger owner
            before_save :set_tag_owner
            def set_tag_owner
              self.tag_types.each do |tag|
                tag_type = tag.to_s
                # Set the owner of some tags based on the current tag_list
                set_owner_tag_list_on(owner, :"#{tag_type}", self.send(:"#{tag_type.chop}_list"))
                # Clear the list so we don't get duplicate taggings
                self.send(:"#{tag_type.chop}_list=",nil)
              end
            end
    
          end
        end
      end
    

    Usage Instructions:

      Given: A model, Post, that is taggable
             A model, User, that is the tag owner
             A post is owned by the user through a relationship called :owner
      Then add to Post.rb:
             include Tagger
             acts_as_taggable_on :skills, :interests, :tags
             tagger :owner
      Make sure Post.rb already has called acts_as_taggable_on, and that User.rb has acts_as_tagger
      Note: This supports multiple tag contexts, not just tags (eg skills, interests)..
    

提交回复
热议问题