In a data importer, I have code which is attempting to add a bunch of ActsAsTaggableOn::Tag
objects to a taggable's tag list:
在数据导入器中,我有一些代码试图将一堆ActsAsTaggableOn :: Tag对象添加到taggable的标记列表中:
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
This doesn't work, because tag_list.add
takes a list of tag names, not tag objects. Is there any way to add tag objects? I can't find anything in the acts-as-taggable-on documentation, and its code is much too magic for me to understand (for instance, Tag::concat
doesn't appear to mutate self!)
这不起作用,因为tag_list.add采用标记名称列表,而不是标记对象。有没有办法添加标签对象?我在act-as-taggable-on文档中找不到任何内容,而且它的代码对我来说太难理解了(例如,Tag :: concat似乎没有变异自我!)
I could map the tags to their names, but then acts-as-taggable-on would run name canonicalization that is appropriate for user input but not for bulk data import, so I don't want to do that.
我可以将标签映射到它们的名称,但是然后act-as-taggable-on将运行适合用户输入的名称规范化,但不适用于批量数据导入,因此我不想这样做。
1 个解决方案
#1
3
The gem is really just adding this for you:
宝石真的只是为你添加这个:
has_many :taggings
has_many :tags, through: :taggings
(It's a little more complicated to support multiple kinds of tags, but the details are pretty simple.)
(支持多种标签有点复杂,但细节非常简单。)
So you can use those associations just like any other. In your case it'd be something like:
所以你可以像其他任何一样使用这些关联。在你的情况下,它是这样的:
ActsAsTaggableOn::Tag.where(id: tags_old_to_new(item[:tags], tags))).each do | t|
new_item.tags << t
end
#1
3
The gem is really just adding this for you:
宝石真的只是为你添加这个:
has_many :taggings
has_many :tags, through: :taggings
(It's a little more complicated to support multiple kinds of tags, but the details are pretty simple.)
(支持多种标签有点复杂,但细节非常简单。)
So you can use those associations just like any other. In your case it'd be something like:
所以你可以像其他任何一样使用这些关联。在你的情况下,它是这样的:
ActsAsTaggableOn::Tag.where(id: tags_old_to_new(item[:tags], tags))).each do | t|
new_item.tags << t
end