Ruby on Rails-重新加载部分Click事件时出错

时间:2018-10-09 00:45:53

标签: javascript ruby-on-rails

我正在尝试重新加载表单中使用的部分内容,以便更新视图中“停止时间”字段中显示的时间。

当我尝试在click事件中重新加载部分内容时出现错误。

我已经在SO网站上审查了类似的问题,例如:Rails refresh partial,当我尝试应用其他问题的答案时,我无法解决该错误。

感谢您提供任何有助于解决此错误的评论或建议。

预先感谢您的帮助。

我的应用程序环境是:

  • 发布版本4.2.7.1
  • Ruby版本2.3.4-p301(x86_64-linux)
  • RubyGems 2.6.11版
  • JavaScript运行时Node.js(V8)

我已在控制器中将“ update_stoptime”操作定义为:

class UsercatsController < ApplicationController  
  #######################################
  # define action to update stop time
  #######################################
  def update_stoptime

    @ustoptime = Time.current.strftime("%I:%M %p")

    p 'print @ustoptime time value (Time.current) below for update_stoptime action in Usercats controller'
    p @ustoptime

    respond_to do |format|
        format.js 
    end

  end

# GET /usercats/new
  def new

     p 'current user ID for NEW action is:'
     p current_user.id

     @usercat = current_user.usercats.build

     @ustoptime = Time.current.strftime("%I:%M %p")

     p 'print @ustoptime time value below for new action in controller(Time.current)'
     p @ustoptime

  end

end

该部分文件保存在“ ../views/stoptimes”文件夹下:

# _stoptime.html.erb

<div id='update_stoptime'>
   <%= f.input :stoptime, required: true, input_html: {value: @ustoptime}, :label => "Stop Time:", :ampm => true %>
</div>

部分图像是通过保存在../views/usercats文件夹下的文件渲染的:

# _form.html.erb

<%= simple_form_for(@usercat) do |f| %>
    <%= f.error_notification %>

  <div class="form-inputs">
    <%= render 'stoptimes/stoptime', f: f %>
  </div>


  <div class="form-actions">
    <%= f.button :submit %>
  </div>
<% end %>

在../views/usercats文件夹下,我使用以下JS Coffee文件重新加载click事件的部分内容:

# app/views/usercats/update_stoptime.js.coffee

$("#update_stoptime").load("<%= j render partial: 'stoptimes/stoptime',  locals: { f: f } %>");

我用以下行更新了route.rb文件:

get 'usercats/update_stoptime', as: 'update_stoptime'

在“ ../app/assets/javascripts/”文件夹下,我使用AJAX调用创建了JS Coffee文件:

# stoptime.js.coffee

$ ->
  $(document).on 'click', '#update_stoptime', (evt) ->
      $.ajax 'update_stoptime',
      type: 'GET'
     dataType: 'script'
     error: (jqXHR, textStatus, errorThrown) ->
     console.log("AJAX Error: #{textStatus}")
     success: (data, textStatus, jqXHR) ->     
     console.log("script loaded OK!")

我在下面列出了错误:

Started GET "/usercats/update_stoptime?_=1539021470900" for 104.194.218.93 at 2018-10-08 17:58:58 +0000

Processing by UsercatsController#update_stoptime as JS
  Parameters: {"_"=>"1539021470900"}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]

"print @ustoptime time value (Time.current) below for update_stoptime action in controller"
"01:58 PM"
  Rendered usercats/update_stoptime.js.coffee (45.7ms)
Completed 500 Internal Server Error in 53ms (ActiveRecord: 0.2ms)

ActionView::Template::Error (undefined local variable or method `f' for #<#<Class:0x007f736a255078>:0x007f7369f05698>):
  1: # app/views/usercats/update_stoptime.js.coffee
  2: $("#update_stoptime").load("<%= j render partial: 'stoptimes/stoptime',  locals: { f: f } %>");

app/views/usercats/update_stoptime.js.coffee:2:in '_app_views_usercats_update_stoptime_js_coffee___2918126501527502339_70066841111240'
app/controllers/usercats_controller.rb:32:in 'update_stoptime'

########################################### ##################

更新,我在下面添加了一些信息,这些信息用于解决重新加载部分点击事件的错误。

########################################### ##################

我决定根据@IlyaKonyukhov的回答将停止时间存储为字符值。

首先,我在下面生成了迁移,以向模型添加字符停止时间变量。

rails g migration add_cstoptime_to_usercat cstoptime:string

接下来,我更新了JS Coffee文件中“ ../app/assets/javascripts/”文件夹下的AJAX调用,以将实例变量从控制器传递到视图。

#stoptime.js.coffee
$ ->
   $(document).on 'click', '#update_stoptime', (evt) ->
     $.ajax 'update_stoptime',
     type: 'GET'
     dataType: 'script'
     data: {
             cstoptime: @ustoptime
           } 
    error: (jqXHR, textStatus, errorThrown) ->
      console.log("AJAX Error: #{textStatus}")
    success: (data, textStatus, jqXHR) ->
      console.log("script loaded OK!")

接下来,我更新了控制器中的“ new”和“ update_stoptime”操作,以输出停止时间的字符串值。

class UsercatsController < ApplicationController  
  #######################################
  # define action to update stop time
  #######################################
  def update_stoptime

    @ustoptime = Time.current.strftime("%I:%M %p").to_s

    p 'print @ustoptime time value (Time.current) below for update_stoptime action in Usercats controller'
    p @ustoptime

    respond_to do |format|
        format.js 
    end

  end

# GET /usercats/new
  def new

     p 'current user ID for NEW action is:'
     p current_user.id

     @usercat = current_user.usercats.build

     @ustoptime = Time.current.strftime("%I:%M %p").to_s

     p 'print @ustoptime time value below for new action in controller(Time.current)'
     p @ustoptime

  end

end

接下来,我更新了保存在“ ../views/stoptimes”文件夹下的部分文件:

#app/views/stoptimes/_stoptime.html.erb
<input value="<%= @ustoptime %></input>

接下来,我更新了JS Coffee文件,以在click事件上重新加载停止时间值:

# app/views/usercats/update_stoptime.js.coffee
$("#update_stoptime").val("<%= @ustoptime %>");

接下来,我更新了保存在../views/usercats文件夹下的表单:

# _form.html.erb

<%= simple_form_for(@usercat) do |f| %>
    <%= f.error_notification %>

 <%= f.input :cstoptime, :label => "Record stop time:",  
           input_html: {id: 'update_stoptime', :style => "width:110px", value:  @ustoptime, class: "form-control"} %>


  <div class="form-actions">
    <%= f.button :submit %>
  </div>
<% end %>

完成上面列出的修订/更新后,停止时间的值开始在click事件上自动更新,没有任何错误。

感谢@IlyaKonyukhov的意见和建议。

2 个答案:

答案 0 :(得分:0)

尝试将其更改为:

$(“#update_stoptime”)。html(“ <​​%= scape_javascript(render部分:'stoptimes / stoptime',本地用户:{f:f})%>”);

答案 1 :(得分:0)

好吧,错误消息undefined local variable or method `f'清楚地表明了问题所在。

响应AJAX对“ usercats / update_stoptime”的请求,服务器将处理此模板:

# app/views/usercats/update_stoptime.js.coffee
$("#update_stoptime").load("<%= j render partial: 'stoptimes/stoptime',  locals: { f: f } %>");

ERB表达式中的变量f是局部的,未在该模板中定义。这就是为什么它会导致错误。

将此场景倒退到为常规GET请求定义了此变量的位置时,会将我们引向_form.html.erb模板,在该模板中将其设置为@usercat形式的块参数。对于您的AJAX调用,@usercat也没有定义。

我建议重写_stoptime.html.erb模板,并将f.input替换为常规text_field_tag(或time_field_tag吗?)。在您的情况下,值是通过@ustoptime变量单独定义的,该变量在常规和AJAX调用的两种控制器方法中均已设置。因此,f变量唯一带来的是input标签的名称。您可以使用对当前代码库的常规GET请求来监视它。