简体   繁体   中英

Why is my partial not rails rendering properly?

I want to add comments without having to refresh the page in my app. However, my partial does no load properly with the JS functionality I am implementing.

I am getting no errors in my log or console, and the comment shows once I refresh the page, but it does not happen without a refresh.

Also, when I just write JS to append the last comment to the win_com id, the code works. I'd like the HTML to dynamically show the current state of the comment partial via JS rather than just append the last comment. Any help would be appreciated! Here's my code:

comments_controller.rb:

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

views/windows/show.html.erb: (part of a larger view)

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

views/windows/_comment.html.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>

views/comments/create.js.erb:

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

application.js:

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

Maybe some key lines from my sever log?:

Rendered windows/_comment.html.erb (0.0ms)
Rendered comments/create.js.erb (1.8ms)

You are missing the @comments instance variable in your controller action create. Rails cannot magically know what it is unless you specify it. Your could change your create action to something like this.

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

.html() will replace all the contents of the target DOM element instead use .append()

Replace this:

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

With that:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM