【问题标题】:Why is this controller returning an html, causing respond_to to fail?为什么这个控制器返回一个 html,导致 respond_to 失败?
【发布时间】:2020-10-31 19:03:16
【问题描述】:

我正在学习一门课程,我们试图通过 response_to 渲染部分内容。我一直严格遵守它,我很困惑为什么我的项目现在显示错误,而导师的项目到目前为止运行良好。

StocksController#search 中的 ActionController::UnknownFormat

由于某种原因,控制器只能响应 html 结果,而不是 js 结果,这就是本课程的内容。我很难理解为什么会这样。

这里是相关的模型、控制器和视图:

app/controllers/stocks_controller.rb

class StocksController <ApplicationController
    
    def search
        if params[:stock].present?            
             @stock = Stock.new_lookup(params[:stock])
             if @stock            
                respond_to do |format|
                    format.js { render partial: 'users/result' }
                end         
             else
                flash[:alert] = "Please enter a valid symbol to search"
                redirect_to my_portfolio_path
             end             
        else 
            flash[:alert] = "Please enter a symbol to search"
            redirect_to my_portfolio_path
        end
    end
    
end

app/models/stock.rb

class Stock < ApplicationRecord
    def self.new_lookup(ticker)
        client = IEX::Api::Client.new(
            publishable_token: Rails.application.credentials.iex_client[:sandbox_publishable_token],
            secret_token: Rails.application.credentials.iex_client[:sandbox_secret_token],
            endpoint: 'https://sandbox.iexapis.com/v1'
        )
        begin
            new(ticker: ticker, name: client.company(ticker).company_name, last_price: client.price(ticker))
        rescue Exception => e
            nil
        end
    end
end

app/views/users/my_portfolio.html.erb

<h1>My Portfolio</h1>
 
<div class='search-area'>
  <h3>Search Stocks</h3>
  <%= form_tag search_stock_path, remote: true, method: :get do %>
    <div class="form-group row">
      <div class="col-sm-9 no-right-padding">
        <%= text_field_tag :stock, params[:stock], placeholder: "Stock ticker symbol", autofocus: true, class: "form-control form-control-lg" %>
      </div>
      <div class="col-sm-3 no-left-padding">
        <%= button_tag type: :submit, class: "btn btn-success" do %>
          <%= fa_icon 'search 2x' %>
        <% end %>
      </div>
    </div>
  <% end %>
</div>
 
<div id="results">
 
</div>

app/views/users/_result.html.erb

<% if @stock %>
  <div class="card card-header results-block">
    <strong>Symbol: </strong> <%= @stock.ticker %>
    <strong>Name: </strong> <%= @stock.name %>
    <strong>Price: </strong> <%= @stock.last_price %>
  </div>
<% end %>

app/views/users/_result.js.erb

alert("Hello!");

据我了解,通过在表格中输入有效的代码,我应该会看到警报,因为这就是教师正在发生的事情。我已经在表单中有remote: true,这是我从其他答案中看到的。

任何帮助将不胜感激。谢谢!

编辑:这是我的 application.js 文件。它已经有建议的需求,我添加的唯一部分是import "bootstrap"

// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")


// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)

import "bootstrap"

编辑 2:这部分的 remote: true 似乎根本不起作用。当我在此问题涉及的部分之前按照讲师的命令进行操作时,不会调用 ajax,并且页面会再次重新加载。

我的意思是页面正在从 /my_portfolio 端点(我开始搜索的地方)加载 /search_stock 端点,而不是停留在 /my_portfolio 并等待 js 响应。不过,表单标签确实正确地将data-remote="true" 显示在检查器中。

【问题讨论】:

  • request.format 输出什么?
  • @JoshBrody >> request.format => #<:type:0x0000000007879360 html>
  • 你的请求是html,而你只有respond_tojs
  • 我明白这一点,我已经在主要问题中提到了这一点。我的问题是问为什么这个请求是作为 html 发送的?我已逐字遵循该讲师的指示,因此您在此处看到的所有内容都是他所写的,但是他显示了在提交有效代码时显示警报的期望输出。我不认为 rails 版本会有所作为,因为我在 6.0.3.2 上,而他也在 6.0.x 分支上。
  • @JoshBrody 我的理解是通过将remote: true 添加到表单标签中,这将强制请求成为AJAX 调用并返回一些javascript。

标签: ruby-on-rails ruby respond-to


【解决方案1】:
const { environment } = require('@rails/webpacker')

const webpack = require("webpack")

environment.plugins.append("Provide", new webpack.ProvidePlugin({
    $: "jQuery",
    jQuery: "jQuery",
    Popper: ["popper.js", "default"]
}))

module.exports = environment

我的 environment.js 文件在字符串中引用了 jQuery,而它应该改为 jquery,没有大写 Q。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 2013-07-04
    • 1970-01-01
    • 2022-02-01
    • 2018-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多