在数据导入程序中,我有一些代码试图将一组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这不起作用,因为tag_list.add使用的是标记名列表,而不是标记对象。有什么方法可以添加标记对象吗?我在acts上的文档中找不到任何东西,而且它的代码太神奇了,我无法理解(例如,Tag::concat似乎没有变异self!)
我可以将标记映射到它们的名称上,但之后,就会运行适合用户输入但不适合大容量数据导入的名称规范化,所以我不想这样做。
发布于 2018-01-16 22:46:31
gem实际上只是为您添加了以下内容:
has_many :taggings
has_many :tags, through: :taggings(支持多种类型的标记要复杂一些,但是细节非常简单。)
所以你可以像其他人一样使用这些关联。在你的情况下,会是这样的:
ActsAsTaggableOn::Tag.where(id: tags_old_to_new(item[:tags], tags))).each do | t|
new_item.tags << t
endhttps://stackoverflow.com/questions/47740207
复制相似问题