Question

When I loading my web page it fetching data form ebay.in it ok.

But data is not showing in different row. I want to show like:

   CATEGORY LISTS

      Samsung
      Nokia
      Apple
      HTC
      Sony
      Blackberry 

But showing like:

    CATEGORY LISTS
   Samsung Nokia Apple HTC Sony Blackberry

because all data saving in one ID of category in one name.

My code :

           class Category < ActiveRecord::Base
           has_many :products


             url ="http://www.ebay.in/cat/mobiles"
             doc = Nokogiri::HTML(open(url))
             name = doc.css("#brand .nav-tabs-m a").text

             if Category.find_by_name(name).nil?
             Category.create(:name => name)
           end
        end

Please help me solve it.

Was it helpful?

Solution 2

class Category < ActiveRecord::Base
  has_many :products


 url ="http://www.ebay.in/cat/mobiles"
 doc = Nokogiri::HTML(open(url))
 name = doc.css("#brand .nav-tabs-m a")

 name.each do |category_name|
   name = Nokogiri::HTML(category_name.content).text
   if Category.find_by_name(name).nil?
     Category.create(:name => name)
  end
 end

end

OTHER TIPS

hm. If I unserstand you right.

your result seems like this:

=> "\n    \t\t\t\t\t\t\t\n\t\t\t\t\t\t\tSamsung\n  \t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tNokia\n  \t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tApple\n  \t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tHTC\n  \t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tSony\n  \t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tBlackberry"

Try THIS:

?> >> name.gsub(/\s+/, " ")

get's this:

=> "Samsung Nokia Apple HTC Sony Blackberry"

Then you can take each word and put it in an array:

"Samsung Nokia Apple HTC Sony Blackberry".split(/\W+/)

Which gets this:

["Samsung", "Nokia", "Apple", "HTC", "Sony", "Blackberry"]

then you can do this:

["Samsung", "Nokia", "Apple", "HTC", "Sony", "Blackberry"].each do |manufacturer_name|
  Category.create(name: manufacturer_name)
end

Then you have six Categories in your db

Category.count # returns 6
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top