为什么我的部分轨道渲染不正确?

时间:2016-01-05 21:30:27

标签: javascript ruby-on-rails ruby ajax partials

我想添加评论,而无需在我的应用中刷新页面。但是,我的部分没有正确加载我正在实现的JS功能。

我的日志或控制台没有出现任何错误,一旦我刷新页面就会显示注释,但如果没有刷新就不会发生。

此外,当我只是编写JS以将最后一条评论附加到win_com id时,代码可以正常工作。我希望HTML能够通过JS动态显示注释部分的当前状态,而不是仅添加最后一条注释。任何帮助,将不胜感激!这是我的代码:

comments_controller.rb:

<android.support.v7.widget.RecyclerView
    android:id="@+id/drawerList"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/nav_header_container"
    android:layout_above="@+id/hello"
    android:layout_marginTop="15dp" />

<TextView
    android:id="@+id/hello"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="15dp"
    android:paddingLeft="5dp"
    android:text="Hello"
    android:layout_alignParentBottom="true"
    android:textColor="#000"
    android:textStyle="italic" />

views / windows / show.html.erb :(大视图的一部分)

def create
    @window = Window.find(params[:window_id])
    @comment = @window.comments.build(comment_params)
    @comment.user_id = current_user.id

    if @comment.save
        respond_to do |format|
            format.html { redirect_to post_path(@post) }
            format.js 
        end
    end
end

视图/窗/ _comment.html.erb:

<div class="row col-md-7" id="win_com">
    <h4>User Comments</h4>
    <%= render partial: '/windows/comment', collection: @comments %>
</div>

视图/评论/ create.js.erb:

<div class="container">
    <div class="row col-md-7">
        <p><%= comment.body %></p> 
        <p><%= link_to "Delete", [comment.window, comment], method: :delete,
                                                            data: {confirm: "Are you sure?"} %></p>
    </div>
</div>

的application.js:

$('#win_com').html("<%= j render(partial:'/windows/comment', collection: @comments)%>");

也许我的服务器日志中有一些关键行?:

//= require jquery
//= require jquery_ujs
//= require bootstrap-sprockets
//= require turbolinks
//= require_tree .

2 个答案:

答案 0 :(得分:1)

您在控制器操作创建中缺少@comments实例变量。除非你指定它,否则Rails不能神奇地知道它是什么。您可以将创建操作更改为此类操作。

def create
    @window = Window.find(params[:window_id])
    @comment = @window.comments.build(comment_params)
    @comment.user_id = current_user.id

    if @comment.save
        @comments = @post.comments //given that this is defined. 
        respond_to do |format|
            format.html { redirect_to post_path(@post) }
            format.js 
        end
    end
end

答案 1 :(得分:0)

.html()将替换目标DOM元素的所有内容,而不是使用.append()

替换它:

$('#win_com').html( "<%= j(render(partial:'/windows/comment', collection: @comments)) %>" );

有了这个:

$('#win_com').append( "<%= j(render(partial:'/windows/comment', collection: @comments)) %>" );
相关问题