Ask A Question

Notifications

You’re not receiving notifications from this thread.

Updating a genre in a nested association

Wes 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
Reply

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
Reply

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)
Reply
Join the discussion
Create an account Log in

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

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

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