【问题标题】:Send JSON response from helper to #create in Rails从帮助程序发送 JSON 响应到 Rails 中的#create
【发布时间】:2018-01-27 18:04:50
【问题描述】:

在将这些拼图拼凑在一起时遇到一些问题...我正在抓取一个网站以获取一组字符串,我希望将数组发送回我的 React 客户端以供使用。这就是我所拥有的

index.js

componentDidMount() {
    const { restaurant } = this.state

    axios.post('/api/scraper', { restaurant: restaurant })
    .then((res) => {
         console.log(res.data);
    })
}

app/controllers/api/scraper_controller.rb

class Api::ScraperController < ApplicationController
    respond_to :json

    def create
        @info = helpers.get_info(params[:restaurant])
        respond_with @info
    end

end

app/helpers/api/scraper_helper.rb

module Api::ScraperHelper

    def get_info(restaurant)
        puts restaurant

        require 'openssl'
        doc = Nokogiri::HTML(open('http://www.subway.com/en-us/menunutrition/menu/all', :ssl_verify_mode => OpenSSL::SSL::VERIFY_NONE))

        @items = []
        doc.css('.menu-cat-prod-title').each do |item|
            @items.push(item.text)
        end
    end

end

整个想法是将 @items 数组发送回我的 React 页面上的 axios 请求

【问题讨论】:

  • 您是否尝试将@items 添加为要返回的get_info 方法的最后一行?或使用Array#map
  • @SebastianPalma 我尝试在我的get_info 函数中添加respond_with @items,但我收到了undefined method 错误

标签: ruby-on-rails ruby ajax reactjs axios


【解决方案1】:

您的实际代码将仅返回 0,因为在这种情况下,在 Nokogiri::XML::NodeSet 中应用 each 的结果为 0,这就是您在方法中最后执行的“一段代码”留下的内容,所以 Ruby 会返回这个。

如果你在最后一行添加@items,那么这将被返回,你会得到["Black Forest Ham", "Chicken &amp; Bacon Ranch Melt", ...],我猜这就是你需要的:

@items = []
doc.css('.menu-cat-prod-title').each { |item| @items.push(item.text) }
@items

请注意,您还可以对 doc.css('.menu-cat-prod-title') 执行映射操作,然后可以将其分配给任何实例变量:

def get_info(restaurant)
  ...
  doc.css('.menu-cat-prod-title').map(&:text)
end

我想从创建返回数据你可以使用类似render json: { items: @items }的东西,因为项目包含一个菜单数组。

【讨论】:

  • 太棒了,谢谢!我收到了nil 回复,您的render json: { items: @items } 但是,我现在通过以下方式修复:render json: { items: helpers.get_info(params[:restaurant]) }
  • 很高兴能提供帮助,我刚刚尝试了一个“普通”的 ruby​​ 文件,可能是因为缺少输入。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-26
相关资源
最近更新 更多