【问题标题】:Rails - handling an Ajax destroy call on a polymorphic associationRails - 处理多态关联上的 Ajax 销毁调用
【发布时间】:2012-09-06 01:44:22
【问题描述】:

我试图通过 Ajax 销毁评论。在我的应用程序中,我的评论模型使用了多态关联。使用下面的代码成功删除评论(在数据库中)。但是,当我调用 destroy.js.erb 时,它什么也没做,我认为问题在于 dom_id 与 HTML id 不匹配,因此它没有更新。我想我正在经历与@mu_is_too_short 在answer to this question 中表达的相同的事情。不过,我需要有关如何解决此问题的帮助。我不知道解决方案是否涉及 a) 以某种方式将局部变量注释传递给 destory.js.erb 或 b) 另一个解决方案。

routes.rb

resources :feeds do
  resources :comments
end

destroy.js.erb

 $('#<%= dom_id(@comment) %>')
   .fadeOut ->
   $(this).remove()

_comment.html.erb

 <div id=<%= dom_id(comment) %> class="comment">
   <em>on <%= comment.created_at.strftime('%b %d, %Y at %I:%M %p') %></em>
   <%= link_to "Remove", [@commentable, comment], :method => :delete, :remote => true %>
   <%= simple_format comment.content %>
 </div>

feeds/show.html.erb

 <div id="comments">
    <%= render @comments %>
 </div>

评论控制器

 class CommentsController < ApplicationController

   def create
     @comment = @commentable.comments.new(params[:comment])
     if @comment.save
        respond_to do |format|
           format.html { redirect_to @commentable }
           format.js
        end
     else
        render :new
     end
    end

    def destroy
      @comment = Comment.find(params[:id])
      @commentable = @comment.commentable
        if @comment.destroy
          respond_to do |format|
            format.html { redirect_to @commentable }
            format.js
          end
        end
     end
  end

Feed 控制器

 class FeedsController < ApplicationController
  def show
     @feed = Feed.find(params[:id])
     @commentable = @feed
     @comments = @commentable.comments
     @comment = Comment.new
   end
 end

【问题讨论】:

    标签: javascript ruby-on-rails ajax ruby-on-rails-3 polymorphic-associations


    【解决方案1】:

    从外观上看,@comment 将在您到达 destroy.js.erb 时包含注释,因为您在此之前在控制器中设置了它,所以我认为它与引用的答案没有任何关系.我想知道这是否是由于您的 id 周围缺少引号引起的:&lt;div id=&lt;%= dom_id(comment) %&gt; class="comment"&gt;... 我怀疑如果您更正此问题以及任何其他相关的 HTML 验证错误,它将开始工作。

    【讨论】:

    • 谢谢。是的,这是一个问题。我还意识到我正在将咖啡脚本混合在一个 erb 文件中。一旦我清理了这两个问题,它就起作用了。感谢您的帮助。
    • @diasks2 你能帮帮我吗:) stackoverflow.com/questions/18048284/…
    猜你喜欢
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多