当我加载网页时,它会从ebay.in中获取数据
但数据并没有显示在不同的行中。我想显示为:
CATEGORY LISTS
Samsung
Nokia
Apple
HTC
Sony
Blackberry
但显示为:
CATEGORY LISTS
Samsung Nokia Apple HTC Sony Blackberry
因为所有数据都保存在一个名称中的类别的一个ID中。
我的代码:
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
请帮我解决它。
hm。如果我没听错你的话。
你的结果是这样的:
=> "n tttttttntttttttSamsungn tttttttttntttttttNokian tttttttttntttttttApplen tttttttttntttttttHTCn tttttttttntttttttSonyn tttttttttntttttttBlackberry"
试试这个:
?> >> name.gsub(/s+/, " ")
这是:
=> "Samsung Nokia Apple HTC Sony Blackberry"
然后你可以把每个单词放在一个数组中:
"Samsung Nokia Apple HTC Sony Blackberry".split(/W+/)
得到这个:
["Samsung", "Nokia", "Apple", "HTC", "Sony", "Blackberry"]
那么你可以这样做:
["Samsung", "Nokia", "Apple", "HTC", "Sony", "Blackberry"].each do |manufacturer_name|
Category.create(name: manufacturer_name)
end
那么你的数据库中有六个类别
Category.count # returns 6
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
结束