【问题标题】:Rails "acts-as-taggable-on": how to add tag *objects* to taggables, not by nameRails “acts-as-taggable-on”:如何将标签 *objects* 添加到可标记对象,而不是按名称
【发布时间】:2017-12-10 15:16:38
【问题描述】:

在数据导入器中,我的代码试图将一堆 ActsAsTaggableOn::Tag objects 添加到可标记的标签列表中:

    existing_item = FeedItem.where(url: item[:url]).first

    if existing_item.nil?
      new_item = FeedItem.new

      new_item.attributes = item.except(:id, :feeds)

      new_item.feeds = Feed.where(id: feeds_old_to_new(item_feeds, feeds))
      new_item.tag_list.add(
          ActsAsTaggableOn::Tag.where(id: tags_old_to_new(item[:tags], tags)))

      new_item.save!
   else
      # ... merge imported record with existing item ...
   end

这不起作用,因为tag_list.add 需要一个标签列表names,而不是标签objects。有没有办法添加标签objects?我在acts-as-taggable-on 文档中找不到任何内容,而且它的代码太神奇了,我无法理解(例如,Tag::concat 似乎没有自我变异!)

我可以将标签映射到它们的名称,但作为可标记的操作会运行适合用户输入但不适用于批量数据导入的名称规范化,所以我不想这样做。

【问题讨论】:

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


    【解决方案1】:

    gem 真的只是为你添加了这个:

    has_many :taggings
    has_many :tags, through: :taggings
    

    (支持多种标签有点复杂,但the details很简单。)

    因此,您可以像使用其他关联一样使用这些关联。在你的情况下,它会是这样的:

    ActsAsTaggableOn::Tag.where(id: tags_old_to_new(item[:tags], tags))).each do | t|
      new_item.tags << t
    end
    

    【讨论】:

    • 我清楚地记得做某事让我相信FeedItem 对象没有拥有 tags 属性。 the definition of FeedItem 中有一些奇怪的东西——具体看看它对 :tag_context_hierarchy 做了什么。您能否就您的答案中可能需要更改的内容提供任何其他建议以应对该问题?
    • 它有一个简单的acts_as_taggable declaration。我在tag_context_hierarchy 中看不到任何可以改变它的东西。可以看到it even uses the tags association itself
    • 嗯,好的。这些信息足以让我相信这应该起作用。我错误地安排了赏金;再过一个月左右,我将无法对此进行测试。我将继续为您提供赏金,但在我实际测试之前不要接受答案。
    • 我认为您不必担心这一点。 acts_as_api 控制在呈现 HTTP 响应时如何将实例序列化为 JSON,但它不会取代 tags 方法。 (对吧?我没用过,但我看了看它的文档。)
    猜你喜欢
    • 1970-01-01
    • 2011-04-08
    • 1970-01-01
    • 2011-06-03
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多