Loading additional comments using AJAX in Rails

I am currently using a blog site using Ruby on Rails. Each "Mail" has some comments. Currently, I am only uploading the last 5 comments, but I want to implement a hyperlink that will load the rest of the comments. Unfortunately, with my current implementation, all I get is a bunch of unnecessary pluses.

Before

Comments

Posted 7 minutes ago 
New

Posted 1 day ago 
Comment 3

Posted 1 day ago 
Comment 2

Posted 1 day ago 
Comment 1

Posted 1 day ago 
This is a new comment

View more comments

After clicking the "View Comments" button

Comments

try { Element.insert("comments", { bottom: "
\n
\n Posted 1 day ago\n 
\n Comment 2\n

\n
" }); Element.insert("comments", { bottom: "
\n
\n Posted 1 day ago\n 
\n Comment 3\n

\n
" }); Element.insert("comments", { bottom: "
\n
\n Posted less than a minute ago\n 
\n New\n

\n
" }); Element.hide("morecomments"); } catch (e) { alert('RJS error:\n\n' + e.toString()); alert('Element.insert(\"comments\", { bottom: \"
\\n
\\n Posted 1 day ago\\n 
\\n Comment 2\\n

\\n
\" });\nElement.insert(\"comments\", { bottom: \"
\\n
\\n Posted 1 day ago\\n 
\\n Comment 3\\n

\\n
\" });\nElement.insert(\"comments\", { bottom: \"
\\n
\\n Posted less than a minute ago\\n 
\\n New\\n

\\n
\" });\nElement.hide(\"morecomments\");'); throw e }

The message show.html.erb has:

<div id="morecomments">
  <%= link_to_remote "View more comments", :url=>{:action=>'morecomments',:post_id=>@post.id},:update=>'comments' %>
</div>

My message controller has

def morecomments
  @post = Post.find(params[:post_id])
  @comments = @post.comments.values_at(Range.new(5, @post.comments.size-1))
  respond_to do |format|
    format.html {redirect_to @post.comments}
    format.js
  end
end

And finally, my morecomments.js.rjs:

@comments.each do |p|
  page.insert_html :bottom, :comments, :partial => p
end
page.hide 'morecomments'

I'm really new to Rails, and I really don't know what all meta-magic rails do in the background. Any help would be awesome.

Thank!

+3
2

, . link_to_remote : update RJS. .

link_to_remote : update, html, html DOM, , : update. div.

.js rjs, - , javascript, link_to_remote html div.

:

  • link_to_remote :update

    , rjs . , foramt.js :

     format.js { render :partial => 'comments', :collection => @comments}
    
  • RJS

    . , , , :update =>'comments' link_to_remote.

+4

, javascript .

, .js, javascript. , javascript, . json javascript , . , script, () .

-1

Source: https://habr.com/ru/post/1730305/


All Articles