【发布时间】:2015-01-05 21:28:30
【问题描述】:
我想从网站获取内容,输入到提交表单中,并将该信息存储为 json,我可以将其保存到我的数据库中。我正在尝试使用 HTTParty,但我不太确定如何实现它来获取数据。这是我目前所拥有的。
控制器
class UrlsController < ApplicationController
before_action :set_url, only: [:show, :edit, :update, :destroy]
#require "addressable/uri"
#Addressable::URI.parse(url)
# GET /urls
# GET /urls.json
def index
@urls = Url.all
end
# GET /urls/1
# GET /urls/1.json
def show
end
# GET /urls/new
def new
@url = Url.new
end
# GET /urls/1/edit
def edit
end
def uri?(string)
uri = URI.parse(string)
%w( http https ).include?(uri.scheme)
rescue URI::BadURIError
false
rescue URI::InvalidURIError
false
end
# POST /urls
# POST /urls.json
def create
@url = Url.new(url_params)
@app_url = params[:url]
respond_to do |format|
if @url.save
format.html { redirect_to @url, notice: 'Url was successfully created.' }
format.json { render action: 'show', status: :created, location: @url }
wordcount
else
format.html { render action: 'new' }
format.json { render json: @url.errors, status: :unprocessable_entity }
end
end
end
def wordcount
# Choose the URL to visit
@app_url = @url
@words = HTTParty.get(@app_url)
# Trick to pretty print headers
@wordcount = Hash[*@words]
end
# PATCH/PUT /urls/1
# PATCH/PUT /urls/1.json
def update
respond_to do |format|
if @url.update(url_params)
format.html { redirect_to @url, notice: 'Url was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @url.errors, status: :unprocessable_entity }
end
end
end
# DELETE /urls/1
# DELETE /urls/1.json
def destroy
@url.destroy
respond_to do |format|
format.html { redirect_to urls_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_url
@url = Url.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def url_params
params.require(:url).permit(:url)
end
end
那是我的controller.rb。我从@words = HTTParty.get(@app_url) 行中得到一个“错误参数(预期的 URI 对象或 URI 字符串)”我需要将表单中的 url 更改为有效的 URL,从该 URL 中获取我想要的内容,然后保存信息。
【问题讨论】:
-
您的要点似乎无效,为什么不将您的代码放入堆栈?
-
为什么要把你的数据转成JSON然后存入数据库呢?这使得数据难以重用。从数据创建 JSON 很容易。
-
我想从输入的每个站点中获取一个列表词,以便以后查看。存储在哈希中不是最好的方式吗?
标签: ruby-on-rails ruby json ruby-on-rails-4 httparty