我正在制作带有视频的网站。每个视频都可以在show.html.erb中注释。因为评论的数量可能很大,所以我使用will_paginate对评论进行了分页。在创建/删除新评论时,我想更新评论列表和分页栏。我无法管理评论和分页,无法远程更新并且运作良好。
我的模特
class Video < ActiveRecord::Base
attr_accessible :description, :name, :src, :rating, :tag_list
acts_as_taggable
belongs_to :user
has_many :comments
validates :rating, presence: true, numericality: {:greater_than_or_equal_to => 0, :less_than_or_equal_to => 1000000}
validates_uniqueness_of :src
validates :name, presence: true
validates :src, presence: true
after_initialize :init
def init
self.rating ||= 0 #will set the default value only if it's nil
end
end
我查看了视频/ show.html.erb
<p>Name: <%= @video.name %></p>
<p>Description: <%= @video.description %></p>
<div id="comments_form">
<%= render :partial => "comments/comment",
:collection => @comments %>
<%= will_paginate @comments %>
</div>
<div id="new_comment_form">
<%= render "comments/form" if current_user%>
</div>
我有部分评论/ _form.html.erb
<%if @user%>
<%= form_for([@video.user, @video, @video.comments.build], remote: true) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<br />
<div class="field">
<%= f.label "Сообщение" %>
<br />
<%= f.text_field :body %>
<br/>
</div>
<div class="actions">
<%= submit_tag "Добавить сообщение", class: "btn btn-large btn-primary" %>
</div>
<% end %>
<%end%>
我的评论/ _comment.html.erb
<p>
<%if comment.user%>
<b><%= comment.user.name %></b> (создано <%= time_ago_in_words(comment.created_at) %> назад):
<%end%>
<%= comment.body %>
<%if comment.user == current_user%>
<%= link_to "Удалить сообщение", [comment.video.user, comment.video, comment],
:confirm => "Уверен?",
:method => :delete, remote: true %>
<%end%>
</p>
我有控制器控制器/ comments_controller.rb
class CommentsController < ApplicationController
...
def create
@video=Video.find(params[:video_id])
@comment = @video.comments.new(params[:comment])
@comment.user = current_user
@video=Video.find(params[:video_id]) unless @comment.save
@comments = @video.comments.paginate(page: params[:page], per_page: 10, order: 'created_at DESC')
respond_to do |format|
format.js
end
end
...
end
我有评论\ create.js.erb
$("#comments_form").html("<%= escape_javascript(render :partial => "comments/comment",
:collection => @comments) %><%= escape_javascript(will_paginate @comments) %>")
一切都很棒:我的新评论已创建,我的分页栏已更新,但链接而不是/ users / 1 / videos / 17?page = 1是/ users / 1 / videos / 17 / comments?page = 1 我努力了两天才弄清楚如何解决这个问题,但没有用......
答案 0 :(得分:1)
这是因为分页栏在视频/评论#create中更新。默认情况下,分页控制器/操作是当前控制器的索引。您可以使用will_paginate params option生成分页链接时强制执行控制器/操作。
TBH,我会考虑使用视频/评论#index来列出评论而不是视频#show。