All threads / Updating a genre in a nested association

Ask A Question

Notifications

You’re not receiving notifications from this thread.

Updating a genre in a nested association

Wesly Mezarina asked in General

I've been asking a few question on scraping and nested association. Im running into another issue which is updating genres to each anime.
I'm getting a list of genres, for example "Action, Romance, Drama" and I'm separating each one as so genre_text.strip.split(' ').
I'll just show all my code for a better understanding below. I keep getting an error undefined methodeach' for #`. I tried putting it in a do block but i just updates it all in an array. I'll show how i had it in a do block as well.
Is there a way that I can update each one with a separate genre to each anime?

rake file

genre_scrape = doc.css('div#content .borderClass .js-scrollfix-bottom div:contains("Genres")').text.split(' ')[1..-1]
genre_text = genre_scrape.blank? ? "" : genre_scrape.join(' ').strip.split(' ')
genre = Genre.find_or_create_by(title: genre_text)
anime.update(genres: genre )

With do block

genre_scrape = doc.css('div#content .borderClass .js-scrollfix-bottom div:contains("Genres")').text.split(' ')[1..-1]
genre_text = genre_scrape.blank? ? "" : genre_scrape.join(' ').strip
genres = []
genre_single = []
genre_text.strip.split(' ').each do |g|
 genre_single << g.gsub(/\,/,"")
end
Genre.find_or_create_by(title: genre_single) do |genre|
 genres << genre
end
anime.update(genres: genres )

Genre model

class Genre < ActiveRecord::Base
 has_and_belongs_to_many :animes
end

Anime model

class Anime < ActiveRecord::Base
 has_and_belongs_to_many :genres
end

So i figured out how to check each genre in the array with the code below. Now i need to try to figure out how to update the genre to each anime. If i try to put anime.update(genres: genre) where i have the #code i get an error undefined method each for #<Genre:0x007fecaa98a9d8>. I'll keep updating.

genre_text.each do |g|
 genres = g.gsub(/\,/,"")
  Genre.where(title: genres).first_or_create do |genre|
   #code
  end
end

I figured out how to update it to each anime. I'll show my code below.

genre_scrape = doc.css('div#content .borderClass .js-scrollfix-bottom 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)
Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 35,699+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.