Wesly Wesly - 1 year ago 37
Ruby Question

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

I'm scraping a site and I'm collecting the genres for each book. For example I'm getting "Action, Drama, Romance" into a string a now i want to separate each genre to add it to a collection so the book can be in the action list or romance list and so on.

I'm collecting the genre with the code below and it will output "Action, Drama, Romance". I also have a list of Genres that i want to populate with the ones I'm scraping. The code below works but it gets added as

["action", "Romance"]
together. Is there a way to separate this and add each genre separately?

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] )

Book model

class Book < ActiveRecord::Base
has_and_belongs_to_many :genres

Genre model

class Genre < ActiveRecord::Base
has_and_belongs_to_many :books

Answer Source

I figured it out with the code below.

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|
anime.update(genres: genre)