所有js.erb都运行但没有在rails 4中执行

时间:2016-08-21 12:30:31

标签: jquery ajax ruby-on-rails-4 turbolinks

我正在使用rails 4项目,我一直在使用rails Ajax方法将数据从控制器传输到js.erb,这一直都正常。我注意到有一段时间所有的js.erb javascript都停止了工作,但是从服务器查看文件,请求以js的形式发送并正确呈现。

其中一个回复:

Started GET "/comments/new?comment%5Bcommentable_id%5D=26&comment%5Bcommentable_type%5D=Question" for 127.0.0.1 at 2016-08-21 13:11:32 +0100
Processing by CommentsController#new as JS
  Parameters: {"comment"=>{"commentable_id"=>"26", "commentable_type"=>"Question"}}
  User Load (0.5ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 20 ORDER BY "users"."id" ASC LIMIT 1
   (0.2ms)  BEGIN
  SQL (0.3ms)  UPDATE "users" SET "last_requested_at" = $1, "updated_at" = $2 WHERE "users"."id" = 20  [["last_requested_at", Sun, 21 Aug 2016 12:11:32 UTC +00:00], ["updated_at", Sun, 21 Aug 2016 12:11:32 UTC +00:00]]
   (1.3ms)  COMMIT
  User Load (1.0ms)  Select users.* from users, user_categories where user_categories.user_id = users.id and user_categories.category_id in (select user_categories.category_id from user_categories where user_categories.user_id = 20) and users.id not in (20) and users.id not in (SELECT users.id FROM users INNER JOIN relationships ON users.id = relationships.followed_id and relationships.follower_id = 20) group by users.id limit 5
  Rendered comments/_form.html.erb (0.8ms)
  Rendered comments/new.js.erb (2.0ms)
Completed 200 OK in 12ms (Views: 3.6ms | ActiveRecord: 3.3ms)

这发生在所有应用程序js.erb文件中,但资产文件中的所有脚本(vanilar,coffee和jquery)都可以找到。我已经沉迷了几个月了,我无法解决错误。

当我尝试检查表单chrome时,我得到200响应为js但是没有执行,我也尝试了不同的浏览器。

browser xhr inspector

这是新评论new.js.erb

<% if @comment.commentable_type == "Question" %>
    $('#comment-form').append('<%= escape_javascript render("form") %>');
    $('.comment_link').hide();
 <% else %>
    $('#comment-form_<%= @comment.commentable_id %>').append('<%= escape_javascript render("form") %>');
    $('.comment_link').hide();
<% end %>

$('.cancel-comment').click(function() {
  $('#new_comment, .comment-form').hide();
  $('.comment_link').show();
})

这是调用激发Ajax请求的链接:

<%= link_to " Add a comment", new_comment_path(:comment => { :commentable_type => @question.class.name,
                         :commentable_id => @question.id}),
                         :remote => true,
                         :class => "comment_link",
                         id:"comment_link"  %>

控制器方法:

def new
    @comment = Comment.new(comment_params)
    respond_to do |format|
      format.js { render layout: false }
    end
  end

1 个答案:

答案 0 :(得分:3)

从行动中删除。删除respond_to块后,您可以访问js.erb文件。

respond_to do |format|
  format.js { render layout: false }
end