前提・実現したいこと
Ruby on Rails初心者で、アプリケーションを作っています。
ビューでコレクションをレンダリングして表示させようとしているのですが、うまく動作しません。
発生している問題・エラーメッセージ
保存されているデータ数より1回分多くレンダリングされます。
該当のソースコード
show.html.haml
Ruby
1 = render @comments
_comment.html.haml
html
1%h3.name.font-weight-bold.mt-4 2 = comment.name 3 = link_to "Delete", [comment.post, comment], method: :delete, data: { confirm: "Are you sure?" }, class: " text-secondary small" 4%p.body.mt-2= comment.body
保存されているcomment数より1回分多くレンダリングされるため、最後に”Delete”のみが一つ表示されてしまいます。
モデル、コントローラーも追記します。
新規コメントは非同期通信で行っていますが、こちらは問題なく動作します。
ページロードまたはリロード時に上記問題が発生します。
comment.rb
class Comment < ApplicationRecord validates :name, presence: true validates :body, presence: true belongs_to :post end
posts#show viewにコメントを表示させています。
posts_controller.rb
class PostsController < ApplicationController before_action :set_post, only: [:show, :edit, :update, :destroy] def index @posts = Post.all.order("created_at DESC") end def new @post = Post.new end def create @post = Post.new(post_params) if @post.save redirect_to post_path(@post) else render :new end end def show @comment = @post.comments.new @comments = @post.comments end def edit end def update if @post.update(post_params) redirect_to post_path(@post) else render :edit end end def destroy @post.destroy redirect_to root_path end private def set_post @post = Post.find(params[:id]) end def post_params params.require(:post).permit(:title, :body) end end
不要かもしれませんが、comment.js
$(document).on("ajax:success", "#new-comment", function(e) { // create new comment html var html = buildHTML(e.detail[0]); $('.comments').append(html); $('.commentform_name').val(''); $('.commentform_body').val(''); // scroll to the page bottom $('html, body').animate({ scrollTop: $(document).height() },1500); alert("send your comment") console.log(e.detail[0]); }); $(document).on("ajax:error", "#new-comment", function(e) { console.log(e.detail[2]); }); function buildHTML(data){ var html = '<h3 class ="font-weight-bold mt-4">' + data.comment.name + '<a class ="text-secondary small ml-2" data-method="delete" href="/posts/' + data.post_id + '/comments/' + data.comment.id + '">Delete</a>' + '</h3>\n' + '<div class ="mt-2">' + data.comment.body + '</div>\n'; return html; }
試したこと
comment_counter
で確認すると、0〜データ数までレンダリングされていることが分かりました。原因は何でしょうか?
補足情報(FW/ツールのバージョンなど)
Rails 5.2.0
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。