I am making site with videos. Each video could be commented in show.html.erb. Because number of comments could be big I made pagination for comments using will_paginate. When creating/deleting new comments I want to update comments list and pagination bar. I can't manage comments and pagination to be updated remotely and to work well.
My model
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
I have view videos/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>
I have partial comments/_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%>
My comments/_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>
I have controller controllers/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
I have comments\create.js.erb
$("#comments_form").html("<%= escape_javascript(render :partial => "comments/comment",
:collection => @comments) %><%= escape_javascript(will_paginate @comments) %>")
Everything is almost great: my new comment is created, my pagination bar is updated, but links instead of /users/1/videos/17?page=1 are /users/1/videos/17/comments?page=1 I tried hard for two days to find out how to fix this problem, but no use...