如何分离我正在抓取并更新为嵌套属性的一组流派?

How to separate a group of genres I'm scraping and updated to a nested attribute?

我正在抓取一个网站并收集每本书的类型。例如,我将 "Action, Drama, Romance" 放入一个字符串中,现在我想将每个类型分开以将其添加到一个集合中,这样这本书就可以出现在动作列表或浪漫列表等中。

我正在使用下面的代码收集流派,它将输出 "Action, Drama, Romance"。我还有一个流派列表,我想用我正在抓取的流派填充这些流派。下面的代码有效,但它被添加为 ["action", "Romance"] 在一起。有没有办法将其分开并分别添加每个流派?

genre_scrape = doc.css('div#content .borderClass .js-scrollfix-bottom div:contains("Genres")').text.split(' ')[1..-1]

genre = Genre.where(title: genre_scrape).first_or_create
book.update(genres: [genre] )

图书模型

class Book < ActiveRecord::Base
 has_and_belongs_to_many :genres
end

类型模型

class Genre < ActiveRecord::Base
 has_and_belongs_to_many :books
end

您可以检查 genre 中是否有多个流派,如果有,运行 一个将所有流派添加到书中的循环。

我用下面的代码弄明白了。

genre_scrape = doc.css('div:contains("Genres")').text.split(' ')[1..-1]
genre_text = genre_scrape.blank? ? "" : genre_scrape
genre = []    
genre_text.each do |g|
 genres = g.gsub(/\,/,"")
  genre << Genre.where(title: genres).first_or_create do |genre|
   genre
  end
end
anime.update(genres: genre)