Ruby on rails 在js.erb文件中使用jquery呈现部分错误。渲染不是一个函数
下面是文件“Ruby on rails 在js.erb文件中使用jquery呈现部分错误。渲染不是一个函数,ruby-on-rails,ruby,ruby-on-rails-4,Ruby On Rails,Ruby,Ruby On Rails 4,下面是文件“app_erb.js.erb”中的代码 $(function(){ $('.add_more_element').click(function(e){ e.preventDefault(); $(this).siblings('.remove_this_element').show('slow'); $(this).hide('slow'); $(this).closest('.form-group').add(
app_erb.js.erb
”中的代码
$(function(){
$('.add_more_element').click(function(e){
e.preventDefault();
$(this).siblings('.remove_this_element').show('slow');
$(this).hide('slow');
$(this).closest('.form-group').add('<%=j render 'resumes/resume_certification' %>');
});
});
$(函数(){
$('.添加更多元素')。单击(函数(e){
e、 预防默认值();
$(this).同级('.remove_this_元素')。show('slow');
$(this.hide('slow');
$(this).最近('.form group')。添加('');
});
});
我有部分视图/resume/\u resume\u certification.html.erb
但当我加载我的应用程序时,它会给我
命名错误at/恢复/新
未定义的方法“render”
我在使用javascript呈现部分内容的整个过程中缺少了什么 我看到的最好的选择是避免直接将部分加载到字符串中,而是通过ajax加载所述页面(这也将避免在调用函数之前不使用它加载所述部分!) 在新动作中,您将使用该动作渲染该部分。JS 我相信您遇到的问题是,您试图从资产管道中加载
ERB
/Rails
方法
虽然报告确实说您可以在资产管道中使用ERB预处理,但对于如何实现此功能却知之甚少:
资产管道提供了一个连接和缩小或
压缩JavaScript和CSS资产。它还增加了书写的能力
这些资产使用其他语言和预处理器,例如
咖啡脚本、Sass和ERB
我的理解是,直接在资产管道中包含ERB/Rails代码是不可能的,因为它带来了动态复杂性(至少这是我的经验)。相反,您将希望尽可能使JS保持“原生”
--
Ajax
其次,您必须认识到一些非常重要的事情——Javascript是前端。它的设计目的是将事件绑定到元素,并且不直接与Rails后端交互
因此,您需要使用AJAX从服务器中提取所需的数据:
#config/routes.rb
resources :resumes do
collection do
get :resume_certification
end
end
#app/controllers/resumes_controller.rb
Class ResumesController < ApplicationController
def resume_certification
render "resumes/resume_certification"
end
end
#app/assets/javascripts/app.js
$(function(){
$(document).on("click", ".add_more_element", function(e){
e.preventDefault();
$(this).siblings('.remove_this_element').show('slow');
$(this).hide('slow');
$.get( "resumes/resume_clarification", function( data ) {
$(this).closest('.form-group').add(data);
});
});
});
#config/routes.rb
资源:简历可以
收藏办
获得:简历认证
结束
结束
#app/controllers/resume\u controller.rb
类ResumesController
尝试使用双引号
“
尝试得到相同的错误。错误出现在哪一行?错误可能是您试图在JS中使用渲染
。非常感谢。我现在明白了。你的回答会帮助很多人。尽管我的编辑被拒绝(我不能评论它的答案),但我想指出:1)$.get(“resumes/resume\u clearification”[…]如果不是从根url调用脚本,则
可能会导致错误,因此使用路径帮助程序可能会更好,不仅可以避免该错误,还可以在您碰巧更改到特定操作的路由时避免出现问题。2)$(此)
在$内。get回调将不再引用单击的元素。指出这一点,以便其他人可以在复制/粘贴上述代码时诊断他们的问题
render :layout => false
#config/routes.rb
resources :resumes do
collection do
get :resume_certification
end
end
#app/controllers/resumes_controller.rb
Class ResumesController < ApplicationController
def resume_certification
render "resumes/resume_certification"
end
end
#app/assets/javascripts/app.js
$(function(){
$(document).on("click", ".add_more_element", function(e){
e.preventDefault();
$(this).siblings('.remove_this_element').show('slow');
$(this).hide('slow');
$.get( "resumes/resume_clarification", function( data ) {
$(this).closest('.form-group').add(data);
});
});
});