Ask A Question

Notifications

You’re not receiving notifications from this thread.

Nested Comment Threads in Rails - Part 1 Discussion

Greate episode! If I should get this episode a couple of years ago, that may should saved my life jajaja!

So, this is the same logic you are using here in your post and epdisode comments?

Reply

Yep, pretty much.

Reply

Awesome! Thanks for sharing Chris!

Reply

Thanks, very useful

Reply

Woohoo, thanks for doing this!

Reply

Thanks Chris! . This is great!

Reply

For some reason...you often create episodes just fitting in my current needs..thanks.

Reply

Chris as part of the next part2 series, please add the ability to dynamically update without refreshing the page.... Best practice. As i am able to use the reply system, but i hate how the page has to refresh and i have been struggling to have it appear directly on the page without refreshing... That will be helpful!!

Reply

any help on this topic will be helpful

Reply

I can cover that in a follow-up episode. 👍

Reply

Is there a follow-up episode for this? If there is ~ do you know where I can find this?

Reply

Thank you chris for the consideration!!! that why i re-joined:) when you cather to all your user needs, you build a loyal group of people... Thank i am looking forward for the episode... you know when that will be? :) excited!!!

Reply

chris can we also cover auto scrolling when comment meets at end of page, if it has more comments that it will load as user scrolls? maybe on the main page or do it on a pop up when a user clocks view more comments it pops up and then they can see all the comments and as they reach bottom if there is more comment it scrolls?

Reply

Chris for some reason, i can't get stimulus Reply effect to work.... I am able to hide the reply but clicking on it does not do anything .. it does not expand or collapse

This seems to work for me "visibility: hidden" instead of d-none

but when i click reply, that does not work. i stimulus js dont seem to work for me. any debugging tips?

Reply

I'd just throw some console.logs into your JS and see what's getting called and what's not. Then you can figure out what you are missing.

Reply

Very old comment, but I had the same issue and it was the difference between Bootstrap 3 & 4. BS3 uses hidden.

Reply

Hi Chris, would it be worth using the Ancestry gem for nested comments like this?
I've been questioning whether there would be any noticable benefits. Thanks for this!

Reply

Yep, you certainly could. If you need those features it'd be great. Otherwise, there's not a whole lot of difference.

Reply

Hello Christ
I'm using the simplemde editor on my rails 5.0 blog site. simplemde displayed fine under the comment until i added nested comments based on this tutorial. The problem now is only the first reply textarea has simplemde attached to it correctly. but after submiting a first comment when i click reply i just get a basic textarea without simplemde attached to it.
I'm trying to achieve exactly how simplemde is being used with nested comments tread here at goRails

This is what my posts.coffee look like

simplemde = null
cleanupSimpleMDE = ->
  if simplemde?
    simplemde.toTextArea()
    simplemde = null

$(window).on 'popstate', cleanupSimpleMDE
$(document).on 'turbolinks:before-visit', cleanupSimpleMDE

$(document).on 'turbolinks:load', ->
    $mde = $(".simplemde")
    QUEUE = MathJax.Hub.queue
    if $mde.length > 0
        $mde.each (_, el) ->
            simplemde = new SimpleMDE({
                element: el,
                    ......
            })

and my form partial looks looks like this

<%=form_for([commentable, Comment.new], local: true, html: {class: local_assigns[:class], data: {target: local_assigns[:target]}}) do |form| %>
    <p class="message-area"><%=form.text_area :content, class: "simplemde", id: "md-editor"%></p>
    <%=form.hidden_field :parent_id, value: local_assigns[:parent_id]%>
    <p><%=form.error_message_for(:content)%></p>
    <div class="">
        <span class="inline-block p-r-10">
            <%=form.submit "Post reply", class: "btn btn-primary", id: "submit_comment"%>
        </span>
    </div>
<% end %>

Is there something i'm missing? Thanks for your help

Reply

Hey Lunik,

It sounds like SimpleMDE is not getting attached to the hidden reply comment forms.

For GoRails, I had to do this, so it applies SimpleMDE to any visible forms and then it also applied it when you click the Reply link.

Apologizes for the messy code, this could use some refactoring. :)

simplemde = []

cleanupSimpleMDE = ->
  # Clean up if already exists
  if simplemde.length > 0
    for editor in simplemde
      editor.toTextArea()
    simplemde = []

addSimpleMDE = (field) ->
  editor = new SimpleMDE({
    autoDownloadFontAwesome: false,
    element: field,
    toolbar: ["bold", "italic", "heading", "|", "code", "quote", "unordered-list", "ordered-list", "clean-block", "|", "link", "image", "|", "preview", "side-by-side", "fullscreen", "guide"],
    spellChecker: false
    status: false
  })

  simplemde.push(editor)
  return editor

@setupEditors = ->
  for editor in $(".simplemde:visible")
    addSimpleMDE(editor)

  $("[data-behavior='show-comment-form']").on "click", (e) ->
    e.preventDefault()
    reply_link = $(this)
    reply_link.hide()

    form = reply_link.parents(".forum_post").first().find("[data-behavior='comment-form']")
    form.show()
    addSimpleMDE(form.find("textarea")[0])

$(window).on 'popstate', cleanupSimpleMDE
$(document).on 'turbolinks:before-visit', cleanupSimpleMDE

$(document).on 'turbolinks:load', @setupEditors
Reply

Hi Chris, Thank you so much for your quick response, let me try your solution, i will keep you updated.

Reply

Hey Chris, Just to let you know your code above was very helpful in fixing my problem with simplemde not being applied to the reply text area. It works now!
Many thanks :)

Reply

Rather than passing in commentable and parent_id locals to the comments/form partial I tend to build the new Comment object, and pass that through instead. Like this:

<%= render partial: "comments/form", locals: { comment: Comment.new(commentable: @post, parent_id: comment.id) } %>

This way the commentable and parent_id values are always shown in their context (a Comment object), rather than randomly floating around in your views.

I'm curious what you think of this approach, as it doesn't just apply to this particular video but Rails views in general, specifically forms.

I don't know much about how Rails templating works under the hood to say whether this has any impact on performance, etc.

Reply

I have nested routes so everytime I try to render the form I get an error.

How should I change the form to work with nested routes? This line throws an error, since it can't find tasks_comments_path

<%= form_with model: [commentable, Comment.new], local: true do |form| %>

My routes look like this:

  resources :projects do
    resources :project_steps, path: "step", only: [:show, :update]
    resources :tasks do
            resources :comments, module: :tasks
        end
    resources :reviews, only: [:create, :destroy]
  end
Reply

Hey Arnas,

Just make your form match your routes like you normally would:

<%= form_with model: [@project, @task, Comment.new], local: true do |form| %>
Reply

Thank you.

This worked, but I'm still facing an issue with the Tasks::CommentsController, since I can't use Task.friendly.find(params[:task_id]).

My method currently looks like this, but it throws an error, that it can't find the id when using params[:id] and when I use params[:task_id], I get the error undefined method task_url for Class.......

This is the method I'm using:

def set_commentable
 @project = Project.friendly.find(params[:project_id])
 @tasks = @project.tasks.order(:tag)
 @commentable = @tasks.friendly.find(params[:task_id])
end
Reply

Arnas, did you get this to work?

Reply

Great tutorial.

One thing, if you're using rich_text instead of normal text fields for the comment body, then when rendering you'll want to add the id to the render, or else all of the rich_text editors (event the nested ones) will have the same id, and nothing will save.

for app/views/comments/_form.html.erb

<%= form_with model: [commentable, Comment.new], local: true, html: { class: local_assigns[:class], data: { target: local_assigns[:target] } } do |form| %>
  <div class="form-group">
    <%= form.rich_text_area :body, id: local_assigns[:parent_id] %>
  </div>
  <div class="form-group">
    <%= form.hidden_field :parent_id, value: local_assigns[:parent_id] %>
    <%= form.submit class: "btn btn-primary" %>
  </div>
<% end %>
Reply

my tempate import didnt add bootstrap nor device, wonder if i did something wrong.

Reply

This was a very helpful tutrial. It will be nice add on to have this in react and vue.

Reply

what to do in case of such an error?
unknown attribute 'commentable_type' for Comment.

Reply

It sounds like your Comment model doesn't have the commentable_type attribute yet.

Make sure to run your database migrations (rails db:migrate) and try again. If it still gives you the error, then check your database schema file (db/schema.rb) and see if the comments table has a commentable_type column. It probably has not which suggests you need to write a migration that adds it (and potentially the commentable_id column as well).

See the video for how to do this.

Reply

I do everything according to the video - I press the replay and it just takes me up the page. What could be wrong?

Reply

great

Reply

amazing

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 86,946+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.