【问题标题】:Why is this controller variable not getting through to this javascript code?为什么这个控制器变量没有通过这个 javascript 代码?
【发布时间】:2023-04-08 09:51:02
【问题描述】:

我现在正在尝试使用我的 javascript 在单击元素时呈现一个新视图,使用此代码;

$(document).ready(function() {
    $('.link-panel').click( function() {
        window.location.replace('/quotes/'+gon.gon_quote_id);
    });
});

我收到以下错误:

Couldn't find Quote with 'id'=undefined [WHERE "quotes"."user_id" = $1]

quote_controller.rb:

  def show
    @quote = current_user.quotes.find(params[:id])
    gon.gon_quote_id = @quote.id
  end

def index
@quotes = current_user.quotes.all
# how to pass the individual quote object's id to gon here

结束

我认为这一定是我将 url 参数提供给 replace 方法的方式,你能帮我解决我做错了什么吗?

gon 设置工作正常,如警报测试所示。)

谢谢

【问题讨论】:

  • 这个动作的路由文件是什么?在 javascript 控制台中,'/quotes/'+gon.gon_quote_id yield 是什么?
  • 如果 js 文件是你放在 assets 文件夹中的静态文件,那么你根本无法将控制器值传递给这个文件!因为是静态文件...
  • gon_quote_id 似乎在 window.gon={} 中丢失,您是否在正确的页面中检查此内容?
  • 与您当前的代码一样,我知道只有在您当前正在执行 QuoteController#show 操作时才会发生重定向,因为仅在此处定义了 gon.gon_quote_id。希望这会有所帮助!
  • 啊哈!!!,gon_quote_id 在#show 中但不在#index 中,当然因为我没有在#index 中定义它。我想要做的是使用这个js来启用点击索引中显示的报价对象之一,将quote.id传递到/quotes/.. url,以便它重定向到相关报价的报价/显示。

标签: javascript ruby-on-rails gon


【解决方案1】:

您应该在 URL 中使用id 参数:

window.location.replace('/quotes/?id=' + gon.gon_quote_id);

【讨论】:

  • 不再导致ActiveRecord::RecordNotFound in QuotesController#show,但仍会导致undefined,网址为http://localhost:3000/quotes/?id=undefined
  • @jbk 这意味着gon.gon_quote_idundefined。当你做console.log(gon)时你会得到什么?
  • console.log(gon) Object { } undefined 太奇怪了,它是在 5 分钟前定义的,因为我测试它并看到它 rtn 在警报框中的 id,不确定现在发生了什么改变来阻止它被定义。你能从我的代码中看到它现在是如何未定义的吗?谢谢迈克尔
  • @jbk 我不了解 Ruby,所以我想我无法进一步帮助您。
【解决方案2】:

脚本不知道它是为了从 rails 访问变量,你必须这样做:

$(document).ready(function() {
    $('.link-panel').click( function() {
        window.location.replace('/quotes/'+<%= gon.gon_quote_id %>);
    });
});

【讨论】:

    猜你喜欢
    • 2020-05-17
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 2011-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多