如何将结果存入数据库?

How to save results into the database?

我创建了一个网络抓取工具。

我正在努力将结果保存到模型的列中。

如何将报废的结果推送到列中?

你贴图了吗?想了解它,所以我最终可以 post 索引也许......或显示以前保存的结果等......

架构

ActiveRecord::Schema.define(version: 20170308223314) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "links", force: :cascade do |t|
    t.string   "link_info"
    t.string   "date"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end

我要保存到的两列是您在上面的架构中看到的:link_infodate ...

电流控制器

class LinksController < ApplicationController

    def craigslist_scrape
        require 'open-uri'

        url = "https://losangeles.craigslist.org/search/web"

        page = Nokogiri::HTML(open(url))

        @craigslist_info = page.css("ul.rows")

                @link_info = page.css("li.result-row p.result-info a.result-title.hdrlnk")
                @date = page.css("li.result-row p.result-info time.result-date")
    end

end

craiglist_scrape.html.erb

<% @link_info.each_with_index do |link, index| %>
  <h2><%= "Title of the job: #{link.text}" %></h2>
  <p><%= "Date: #{@date[index].text}" %></p>
<% end %>

路线

Rails.application.routes.draw do
    root 'links#craigslist_scrape'
end

型号

class Link < ApplicationRecord
end

在控制器中您可以添加:

def craigslist_scrape
    require 'open-uri'

    url = "https://losangeles.craigslist.org/search/web"

    page = Nokogiri::HTML(open(url))

    @craigslist_info = page.css("ul.rows")

    @link_info = page.css("li.result-row p.result-info a.result-title.hdrlnk")
    @date = page.css("li.result-row p.result-info time.result-date")

    @link_info.each_with_index do |link, index|
      Link.new(:link => link.text, :date => @date[index].text).save
    end

end

我是 Ruby 的新手,对 Rails 了解不多,但是当我尝试将某些内容保存到 "database" 中时,我总是这样做创建一个哈希。例如:

database = {}
puts "What is your name?"
input = gets.chomp
puts "What's your age?"
input_2 = Integer(gets.chomp)
database[input.to_sym] = input_2

在上面的示例中,我创建了一个名为 "database" 的散列,并询问用户的姓名和年龄。将用户名存储为数据库的字符串值,将他们的年龄存储为整数值。我不知道这是否有帮助,就像我说的我对 Ruby.

还很陌生