ruby-on-rails 用户选择时间范围以更新图表时Ruby on Rails 7参数错误(给定0,预期1)

lndjwyie  于 2023-03-20  发布在  Ruby
关注(0)|答案(1)|浏览(169)

希望您能提供帮助,即使是ChatGPT 4也无法解决此问题。
我有一个Ruby on Rails 7应用程序,我正在尝试查询一个API,以根据用户选择的时间范围(例如,7天、30天和90天)拉动商品的销售。
我收到一个参数错误ArgumentError (wrong number of arguments (given 0, expected 1)),但看起来参数是在该行之前传递的:Parameters: {"timeframe"=>"90_days", "static_page"=>{"timeframe"=>"90_days"}},因为我将默认值设置为30天,所以我知道用户选择了90天
我正试图使用刺激和chartkick宝石,使这项工作。任何帮助,在所有是非常感谢!
下面是我最新的_sales_controller. js文件:

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = ["latestSalesChart"]

  updateChart(event) {
    const timeframe = event.target.value;
    console.log("Timeframe dara:", timeframe);  // log the timeframe to the console
    const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

    const body = JSON.stringify({ timeframe });
    console.log("Body Data", body);

    fetch('/home/last_sales_chart', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-CSRF-Token': csrfToken
      },
      body
    })
    .then(response => response.json())
    .then(data => {
      console.log('Response Data');  // log the response data to the console
      console.log(data);  // log the response data to the console
      const chartData = data.chart_data;
      console.log("Chart Data", chartData)
      const chart = Chartkick.charts[this.latestSalesChartTarget.id];
      chart.updateData(chartData);
    })
    .catch(error => console.log(error));
  }
}

下面是我的static_pages_controller.rb文件:

class StaticPagesController < ApplicationController
  def home
    require 'httparty'
    require 'groupdate'

    puts "last sales: #{last_sales_chart}"

   @chart_data = last_sales_chart

    puts "chart data #{@chart_data.inspect}"

  end

  def about
  end

  def last_sales_chart
    timeframe = params[:timeframe]
    timewindow = get_timewindow(timeframe)
    chart_data = generate_chart_data(timewindow)

    return chart_data
  end

  private

  def get_timewindow(timeframe)
    current_day = DateTime.now
    case timeframe
    when "7_days"
      (current_day - 7).strftime("%Y-%m-%d")
    when "30_days"
      (current_day - 30).strftime("%Y-%m-%d")
    when "90_days"
      (current_day - 90).strftime("%Y-%m-%d")
    else
      (current_day - 30).strftime("%Y-%m-%d")
    end
  end

  def generate_chart_data(timewindow)
    puts "Timewindow data #{timewindow}"
    query = {
      query: "query LastSalePrice {
        tokens(where: {fa2_address: {_eq: \"KT1LHHLso8zQWQWg1HUukajdxxbkGfNoHjh6\"},
        events: {timestamp: {}}, last_sale_at: {_gte: \"#{timewindow}\"}},
        order_by: {last_sale_at: desc_nulls_last, last_sales_price: asc}) {
          fa2_address
          last_sale_at
          last_sales_price
          token_id
          name
        }
      }"
    }

    response = HTTParty.post('https://api.teztok.com/v1/graphql',
                             body: query.to_json,
                             headers: { 'Content-Type' => 'application/json' })

    response_body = JSON.parse(response.body)

    data = response_body["data"]["tokens"].map do |token|
      { timestamp: token["last_sale_at"], token_id: token["token_id"],
        last_sales_price: sprintf('%.6f', token["last_sales_price"]/1000000.0) }
    end

    chart_data = []
    data.each do |d|
      chart_data << [d[:timestamp], d[:last_sales_price]]
    end

    return chart_data

  end

end

下面是我的视图partial _last_sales_chart.html.erb文件:

<div class="outside"
  data-controller="latest-sales"
  data-latest-sales-chart-target="latestSalesChart">

  <div class="form-group">
    <%= label_tag 'timeframe', 'Select Timeframe', class: 'form-label' %>
    <%= select_tag :timeframe, options_for_select([['Last 7 Days', '7_days'], ['Last 30 Days', '30_days'], ['Last 90 Days', '90_days']]), data: { action: "change->latest-sales#updateChart" } %>
  </div>

  <div id="latest-sales">
    <h3><a href="https://objkt.com/collection/tezzardz"
           target="_blank" rel="noopener noreferrer" id="nft-name">Tezzardz</a> Sales Over the Last Month</h3>
      <div id="chart">
        <%= line_chart @chart_data, suffix: "ꜩ", id: "latestSalesChart", ytitle: "Last Sales Price ꜩ", points: false %>
      </div>
  </div>
</div>

下面是我的routes.rb文件:

Rails.application.routes.draw do
  draw :madmin
  root "static_pages#home"

  post "/home/last_sales_chart", to: "static_pages#home#last_sales_chart"

  get "/about",  to: "static_pages#about"

end

下面是我的gem文件:

source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby "3.1.2"

gem "rails",                    "7.0.3"
gem "faker",                    "2.21.0"
gem "sassc-rails",              "2.1.2"
gem "sprockets-rails",          "3.4.2"
gem "importmap-rails",          "1.1.0"
gem "turbo-rails",              "1.1.1"
gem "stimulus-rails",           "1.0.4"
gem "jbuilder",                 "2.11.5"
gem "puma",                     "5.6.4"
gem "devise"
gem "bootsnap",                 "1.12.0", require: false
gem "madmin",                   "~> 1.2"
gem 'httparty'
gem 'chartkick'
gem 'groupdate'
gem 'bootstrap',                "~> 5.2.2"
gem "will_paginate-bootstrap-style"

# Bundle and transpile JavaScript [https://github.com/rails/jsbundling-rails]
gem "jsbundling-rails"

group :development, :test do
  gem "sqlite3", "1.4.2"
  gem "debug",   "1.5.0", platforms: %i[ mri mingw x64_mingw ]
end

group :development do
  gem "web-console", "4.2.0"
end

group :test do
  gem "capybara",                 "3.37.1"
  gem "selenium-webdriver",       "4.2.0"
  gem "webdrivers",               "5.0.0"
  gem "rails-controller-testing", "1.0.5"
  gem "minitest",                 "5.15.0"
  gem "minitest-reporters",       "1.5.0"
  gem "guard",                    "2.18.0"
  gem "guard-minitest",           "2.4.6"
end

group :production do
  gem "pg", "1.3.5"
end

下面是我在Rails服务器中遇到的错误:

Processing by StaticPagesController#update_chart_data as */*
  Parameters: {"timeframe"=>"30_days", "static_page"=>{"timeframe"=>"30_days"}}
Completed 500 Internal Server Error in 1ms (ActiveRecord: 0.0ms | Allocations: 802)

  
ArgumentError (wrong number of arguments (given 0, expected 1)):
  
app/controllers/static_pages_controller.rb:17:in `update_chart_data'

谢谢大家!

goqiplq2

goqiplq21#

因为update_chart_data是控制器中的一个action,所以我认为它不应该接收参数,它的声明应该像def update_chart_data,必须直接从params中获取timeframe

相关问题