为什么我的js.erb文件只能在其中一种情况下运行?

时间:2013-12-08 15:23:16

标签: javascript ruby-on-rails erb

我在控制器上执行以下操作以获得评论:

  def create
    @comment = comment.new(params[:comment])
    @comment.replyable_type = params[:replyable_type]
    @comment.replyable_id = params[:replyable_id]
    @comment.user = current_user

    respond_to do |format|
      format.html do
        # Removed
      end
      format.js do
        @comment.save
      end
    end
  end

和以下create.js.erb文件,用于远程表单调用它时:

console.log('It did run');
<% if @comment.errors.any? %>
  <% @comment.errors.full_messages.each do |msg| %>
    console.log('<%= javascript_escape(msg) %>');
  <% end %>
<% else %>
  comment = "<%= escape_javascript render @comment %>";
  <% if @comment.replyable_type == 'Comment' %>
    $('#comment-<%= @comment.id %> > .replies').prepend(comment));
  <% else %>
    $('.comments').prepend(comment);
  <% end %>
  // removed
<% end %>

以下表格部分:

<%= form_for(Comment.new, url: comments_path, remote: true) do |f| %>
  <div class="comment-form" id="comment-<%= replyable_type %>-<%= replyable_id %>">
    <%= f.text_area :content, cols: 60, rows: 5 %>
    <%= hidden_field_tag :replyable_id, replyable_id %>
    <%= hidden_field_tag :replyable_type, replyable_type %>
    <%= f.submit 'Send Comment', class: 'btn btn-primary' %>
  </div>
<% end %>

replyable是一个多态关联,可以是PostComment对象。当我在帖子的页面上提交表单副本时,其中replyable_typePostreplyable_id是帖子的ID,则可以正常使用。当我在同一页面上提交表单副本时,replyable_type设置为Commentreplyable_id设置为注释ID,则javascript无法运行,所有。控制器上的操作运行,使用Firebug我可以看到呈现的javascript被发回以响应post请求,并且注释被添加到数据库中。

用于生成javascript的Rails控制台或用于运行生成的javascript的Firebug控制台中都没有错误。 @comment.errors数组中也没有错误。尽管存在于呈现的javascript中,但即使可回复对象是注释,Javascript中的第一个console.log也不会运行。

是什么导致这个?我在Ruby 1.9.3上使用Rails 3.2.13

0 个答案:

没有答案