2016-06-06 2 views
-2

사이트를 고치고 있으며 각 책의 장르를 수집하고 있습니다. 예를 들어, "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 

답변

0

아래 코드로 알아 냈습니다.

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

당신은 genre 하나 개 이상의 장르를 가지고 있는지 확인 할 수 있도록 책에 모든 장르를 추가하는 루프를 실행하는 경우 .