为什么在使用ajax加载时不会加载部分?

时间:2015-10-26 13:59:49

标签: ruby-on-rails ajax ruby-on-rails-3 ruby-on-rails-4

为什么这不会加载部分?(聊天评论DOM)但它会加载网址/评论。

如何只加载部分?我在这里缺少什么?

的routes.rb

.
.
.
resources :comments
get ":lang/v/:site/:uid/refresh_part_after_comment" => 'movies#refresh_part_after_comment'
get ':lang/v/:site/:uid' => 'movies#show', :via => :get, :as => :watch_v
resources :movies
.
.
.

views / movies / show.html.erb(此处输入表单!)

.
.
.
<div id="chat_comment">
    <%= render 'movies/comment' %>
</div>

<form action="/comments" method="post" data-remote="true" >
    <input type="text" name="body" size="50" id="body_input"/>
    <input type="hidden" name="elapsed_time" id="elapsed_time">
    <input type="hidden" name="video_id" value="<%= params[:uid] %>">
    <button type="submit" >Submit</button>
</form>
.
.
.

comments_controllr.rb

class CommentsController < ApplicationController
    def create

        if @user = User.find_by_twitter_id(session[:id])
        else
            @user = User.new
            @user.twitter_id = session[:id]
            @user.save
        end

        if @movie = Movie.find_by_uid(params[:video_id])

        else
            @movie = Movie.new
            @movie.uid = params[:video_id]
            @movie.save
        end

        @comment = Comment.build_from(@movie, @user.id, params[:body]) 
        @comment.elapsed_time = params[:elapsed_time]
        @comment.save

        flash[:notice] = "posted"       

        respond_to do |format|      
            format.js do
                render 'en/v/yt/' + @movie.uid + '/refresh_part_after_comment'
            end
        end

    end
end

movies_controller.rb

class MoviesController < ApplicationController
    .
    .
    .
    def refresh_part_after_comment
        if @movie = Movie.find_by_uid(params[:uid]) 
            @comments = @movie.comment_threads.order("elapsed_time ASC")
        end

        respond_to do |format|
            format.js 
        end
    end

    def show
        if @movie = Movie.find_by_uid(params[:uid]) 
            @comments = @movie.comment_threads.order("elapsed_time ASC")
        end

        respond_to do |format|
            format.html # show.html.erb
            format.json { render json: @movie }
        end
    end
    .
    .
    .
end

视图/电影/ refresh_part_after_comment.js.erb

$('#chat_comment').html("<%= j(render(:partial => 'movies/comment')) %>");

视图/电影/ _comment.html.erb

<% @comments.each do |comment| %>
    <%= comment.elapsed_time %>_<%= comment.body %><br />
<% end %>

1 个答案:

答案 0 :(得分:1)

如果我理解你,你想在创建评论后显示views/movies/refresh_part_after_comment吗?

render中的CommentsController#create来电似乎没有意义,因为您使用的是网址作为参数:

render 'en/v/yt/' + @movie.uid + '/refresh_part_after_comment'

我认为你需要重定向到新创建的评论。与上面相同的URL应该有效:

redirect_to 'en/v/yt/' + @movie.uid + '/refresh_part_after_comment'