2

私は自分のページにFacebookのようなコメントを実装しましたが、ビューを機能させる方法を見つけようとしています。

コメントがどのように機能するかを示すコードは次のとおりです。

コメントコントローラー

class CommentsController < ApplicationController
     def create
    @micropost = Micropost.find(params[:micropost_id])
    @comment = Comment.new(params[:comment])
    @comment.micropost = @micropost
    @comment.user = current_user
    if @comment.save
       redirect_to(:back)
    else
      render 'shared/_comment_form'
    end
  end
end

コメントフォームビュー

<%= form_for([micropost, @comment]) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
  <div class="field">
    <%= f.text_field :comment_content %>
  </div>
  <button class="btn" type="submit">
    Comment
  </button>
<% end %>

そして、私は提出された後にこれらのコメントを最もよく表示する方法を見つけようとしています。これを使用してビューを作成できますか?

comment.html.erb

  <%= simple_format(comment.content) %>
  <% end %>
4

1 に答える 1

0

このようなことができます

class CommentsController < ApplicationController
     def create
    @micropost = Micropost.find(params[:micropost_id])
    @comment = Comment.new(params[:comment])
    @comment.micropost = @micropost
    @comment.user = current_user
    if @comment.save
       flag = true
    else
      flag = false
    end

respond_to do |format|
 format.html {flag ? redirect_to(:back) : render 'shared/_comment_form'}
format.js
end

  end
end

フォームを ajax 化するように変更する

<%= form_for([micropost, @comment], remote: true) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
  <div class="field">
    <%= f.text_field :comment_content %>
  </div>
  <button class="btn" type="submit">
    Comment
  </button>
<% end %>

次に、ビューを少し編集します

コメント/comment.html.erb

<%= render partial: 'comments/comment', locals: {comment: @comment} %>

そしてパーシャルは

_comment.html.erb

<div id="comment-<%= comment.id%>">
<%= simple_format(comment.content) %>
  <% end %>
</div>

次に、comments/create.js.erb で

$("#comments_container").prepend(' <%=j render partial: "comments/comment", locals: {comment: @comment} %>');

先頭に追加する代わりに、任意の種類のアニメーションを実行できます。コメントの並べ替え方法に応じて、追加することもできます

これにはjQueryを使用していることに注意してください。#comments_container は、コメントを配置する div です。

create.js.erb は基本的に、コメント コントローラーの create アクションの js ビューであるため、create アクションが持つ任意の変数にアクセスできることに注意してください。

注 2: ruby​​ 1.9 ハッシュ形式を使用しています

注 3: コメントに名前を付けた#comment-<%= comment.id %>ので、後で削除したり、別の方法で作業したりした場合にアクセスできます。たとえば、

def destroy

@comment = Comment.find(params[:id])

respond_to do |format|
format.js
end
end

そしてdestroy.js.erbで

$("#comment-<%= @comment.id %>").remove();

そのdivを削除します

jquery_ujs と jquery gem/files があることを確認してください。

于 2013-04-09T06:50:49.633 に答える