【问题标题】:How do I set the tag owner before any tag is saved with the acts-as-taggable gem?如何在任何标签与可标记的 gem 一起保存之前设置标签所有者?
【发布时间】:2016-08-16 19:46:12
【问题描述】:

我正在使用可标记的 gem https://github.com/mbleigh/acts-as-taggable-on 和 jQueryTokenInput 插件为我的图像模型添加标签。到目前为止,标签的创建和添加都很好。我遵循了教程http://bloginius.com/blog/2013/12/31/how-integrate-acts-as-taggable-on-with-jquery-token-input-with-rails-3/。 但是,现在,我希望能够在创建标签时将标签的所有权授予 current_user。 和 gem 的 github 页面一样,我试过了

@some_user.owned_taggings
@some_user.owned_tags

没有令人满意的结果。我继续并在标签表中添加了一个 user_id。是否有一个 tagsController 与acts-as-taggable-on gem 相关联,我可以使用 before_save 修改它以设置标签的 user_id ? 谢谢!!

【问题讨论】:

    标签: ruby-on-rails tags rubygems acts-as-taggable-on


    【解决方案1】:

    section of the acts-as-taggable-on README 专用于所有权,有助于处理模型的细节。

    但是,我不认为提供的方法是正确的——它们会将所有拥有的标签(即由任何人拥有)应用于每个所有者项目关系。这是我的做法:

    DEFAULT_ACTSASTAGGABLEON_TYPE = :tag
    
    module TagToOwner
      extend ActiveSupport::Concern
    
      private
        def add_owned_tag(item, owner, tags_to_add, options = {})
          own_tag(item, owner, arrayify(tags_to_add), "add", options)
        end
    
        def remove_owned_tag(item, owner, tags_to_add, options = {})
          own_tag(item, owner, arrayify(tags_to_add), "subtract", options)
        end
    
        def own_tag(item, owner, tags_to_add, direction = "add", opts)
          tag_type = (options[:tag_type] || DEFAULT_ACTSASTAGGABLEON_TYPE)
          owned_tag_list = item.owner_tags_on(owner, tag_type).map(&:name)
    
          if direction == "subtract"
            owned_tag_list = owned_tag_list.reject{|n| n.in?(tags_to_add)}
          else
            owned_tag_list.push(*tags_to_add)
          end
    
          owner.tag(item, with: stringify(owned_tag_list), on: tag_type, skip_save: (options[:skip_save] || true))
        end
    
        def arrayify(tags_to_add)
          return tags_to_add if tags_to_add.is_a?(Array)
          tags_to_add.split(",")
        end
    
        def stringify(tag_list)
          tag_list.inject('') { |memo, tag| memo += (tag + ',') }.chomp(",")
        end
    end
    

    还有:

    class MyModelController < ApplicationController
      include TagToOwner
      # ...
      def create
        @my_model = MyModel.new(my_model_params)
        add_tags
        # ...
      end
      # ...
      def update
        add_tags
        # ...
      end
    
      private
        def add_tags
          return unless params[:tag_list] && "#{params[:tag_list]}".split(",").any?
          return unless validate_ownership_logic # <- e.g. `current_user`
    
          add_owned_tag(@my_model, current_user, params[:tag_list])
        end
    end
    

    请注意,我已针对acts-as-taggable-on 和a corresponding pull request 提交了an issue 以更正他们的自述文件。

    【讨论】:

      猜你喜欢
      • 2020-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多