首页 > 解决方案 > 为什么这个控制器返回一个 html,导致 respond_to 失败?

问题描述

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

StocksController#search 中的 ActionController::UnknownFormat

StocksController#search 中的 ActionController::UnknownFormat

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

以下是相关的模型、控制器和视图:

应用程序/控制器/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

应用程序/模型/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

应用程序/视图/用户/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>

应用程序/视图/用户/_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 %>

应用程序/视图/用户/_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"显示在检查器中。 Ajax 调用失败

标签: ruby-on-railsrubyrespond-to

解决方案


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。


推荐阅读