AdilA
@AdilA
Нравится кодить, изучаю go c echo

Как сделать views для древовидных комментариев на rails 4?

Доброго времени суток, второй день пытаюсь сделать древовидные комментарии...
В данный момент в тупике.
Итак по существу что сделано:
Создана таблица comments миграции которой прописаны в геме
Файл models/comment.rb

class Comment < ActiveRecord::Base
  acts_as_commentable
  acts_as_nested_set :scope => [:commentable_id, :commentable_type]
  validates :body, :presence => true
  validates :user, :presence => true
  belongs_to :commentable, :polymorphic => true
  belongs_to :user
  # Helper class method that allows you to build a comment
  # by passing a commentable object, a user_id, and comment text
  # example in readme
  def self.build_from(obj, user_id, comment)
    new \
      :commentable => obj,
      :body        => comment,
      :user_id     => user_id
  end
  def has_children?
    self.children.any?
  end
  scope :find_comments_by_user, lambda { |user|
    where(:user_id => user.id).order('created_at DESC')
  }
  scope :find_comments_for_commentable, lambda { |commentable_str, commentable_id|
    where(:commentable_type => commentable_str.to_s, :commentable_id => commentable_id).order('created_at DESC')
  }
  def self.find_commentable(commentable_str, commentable_id)
    commentable_str.constantize.find(commentable_id)
  end
end


Файл models/post.rb
class Post < ActiveRecord::Base
  acts_as_commentable
has_many :comments #не уверен что это нужно, потому что acts_as_commentable загрузил ассоциации
end

Файл controller/comments_controller.rb
class CommentsController < ApplicationController

  def create
    @post = Post.find(params[:post_id])
    @all_comments = @post.comment_threads
    if (params[:comment].has_key?(:parent_id))
      @parent = Comment.find(params[:comment][:parent_id])
    end
    @comment = Comment.build_from(@post, current_user.id, params[:comment][:body])
    if @comment.save
      if @parent
        @comment.move_to_child_of(@parent)
      end
      respond_to do |format|
        format.js
      end
    else
      flash.now[:error] = "Comment was not submitted."
      redirect_to root_path
    end
  end
end

Файл controller/posts_controller.rb
class PostsController < ApplicationController
	def show
		@post = Post.find(params[:id])
		@comments = @post.comment_threads.order('created_at desc')
        @new_comment = Comment.build_from(@post, current_user.id, "")
		#@comments = @post.comment_threads
	end

Файл views/comments/_form.html.erb
<div class='comment-form'>
      <%= form_for([@post, @new_comment], remote: true, html: { class: "comment-reply", id: "replyto_#{comment.id}" }) do |f| %>
          <%= f.text_area :body, :rows => 3 %>
          <%= f.hidden_field :user_id, value: current_user.id %>
          <%= f.hidden_field :parent_id, value: comment.id %>
          <%= f.submit "Комментировать" %>
      <% end %>
</div>

Файл views/comments/create.js.erb
if ("<%= @comment.parent_id %>") {
    $('.comment_<%= @comment.parent_id %>').append("<%= escape_javascript(render partial: 'comment', locals: { comment: @comment } ) %>");

    $("#replyto_<%= @comment.parent_id %>").val('');
    $("#replyto_<%= @comment.parent_id %>").toggle();
}
else {
$('#comments').append("<%= escape_javascript(render partial: 'comment', locals: { comment: @comment } ) %>");

    if ("<%= @comment.body %>") {
        $("#comment_body").val('');
    }
}

Вот это все работает, теперь не могу допереть как написать views для самих comments чтобы были древовидные комментарии c отображением в posts/show.html.erb, и для действия destroy c destroy.js.erb
Пишу на rails 4.0.0.0
Ruby 2.0.0

Помогите, пожалуйста.
  • Вопрос задан
  • 3194 просмотра
Решения вопроса 1
AdilA
@AdilA Автор вопроса
Нравится кодить, изучаю go c echo
Как обычно все банально и просто
надо было создать партиал
<li>
  <p><%= comment.user.name %>: <%= comment.body %>
    </p>

  <p><%= "Replies (#{comment.children.size}): " if comment.has_children? %></p>
  <ol>
    <% comment.children.each do |child_comment| %>
        <li><p><%= child_comment.user.name %>: <%= child_comment.body %>
          </p>
        </li>
    <% end %>
    </ol>
    <%= form_for Comment.new, url: post_comments_path(@post) do |f| %>
    <%= f.hidden_field :parent_id, :value => comment.id %>
      <%= f.text_field :body %>
      <%= f.submit 'Replay' %>
  <% end %>
  </ol>

и прописать правильный render <%= render @post.root_comments %>
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 3
FanKiLL
@FanKiLL
<% @comments.each do |comment| %> #проходимся по комментам
    <%= comment.user.user_name%> # кто написал коммент
    <% if comment.has_children? %>
    	#сделать линк по которому ajax будут забиратся коменты для этой ветки?
        #или делать еще 1 do block и проходить по дочерним комментам.
	<% else %>
  <% end %>


У вас в Классе Comment как я понимаю для этого есть метод has_children?
Ответ написан
FanKiLL
@FanKiLL
Это вообще что то находит?
@parent = Comment.find(params[:comment][:parent_id])


Вы же передаёте parent_id в hiden field
@parent = Comment.find(params[:parent_id])
Может так?
Ответ написан
FanKiLL
@FanKiLL
<%= form_for([@post, @new_comment]) do |f| %>

Вот для этого [@post, @new_comment] рельсы создают своё url что то типа /posts/{post_id}/comments/{comment_id}
Вот оттуда этот паррент id и можно брать.

Добавте в application.html.erb в саммый конец вот это
<%= debug(params) if Rails.env.development? %>

чтобы видеть какие параметры вообще передаются
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы