在内容

时间:2016-03-12 16:05:45

标签: ruby-on-rails ruby

在我的观看中,我有comments/_form.html.erb,还有post posts/show.html的另一个控制器视图。我想在comments/_form.html.erb中呈现posts/show.html,其中显示了与该帖子相关联的个别帖子和评论,并且它已全部设置并正常运行。

我想提供评论和在这些评论下面呈现部分内容的功能,以便我们可以在同一posts/show.html页面上发表新评论,而不是导航到comments/new.html.erb页面。我正在使用嵌套资源,如:

resources :posts do
  resources :comments
end

在我的comments/new.html.erb中,我这样做:

<%= form_for([:post, @comment]) do |f| %>
  ....
<% end %>

我应该如何在posts/show.html.erb页面中呈现它?

1 个答案:

答案 0 :(得分:1)

Javascript是您拼图中缺失的部分。基本上你会做3件事。

  1. 确保您的表单使用js提交(远程)
  2. 确保您的控制器响应js输入
  3. 创建一个将附加每条新评论的js.erb文件
  4. 实施说明: 我可能会做这样的事情:

    将表单添加到视图中,并添加一个包含注释的元素,在本例中,我使用了ul#comments

    # app/views/posts/show.html.erb
    <p>
      <strong>Title:</strong>
      <%= @post.title %>
    </p>
    
    <p>
      <strong>Body:</strong>
      <%= @post.body %>
    </p>
    
    <br/>
    <ul id="comments">
      <%= render @comments %>
    </ul>
    <%= form_for [@post, @new_comment], remote: true do |f| %>
      <%= f.text_field :body %>
      <%= f.submit  %>
    <%end%>
    

    在控制器中添加js响应

    # app/controllers/comments_controller.rb
    def create
      @post = Post.find params[:post_id]
      @comment = @post.comments.new(comment_params)
      @new_comment = @post.comments.new(comment_params)
    
      respond_to do |format|
        if @comment.save
          format.html { redirect_to [@post, @comment], notice: 'Comment was successfully created.' }
          format.json { render :show, status: :created, location: @comment }
          format.js 
        else
          format.html { render :new }
          format.json { render json: @comment.errors, status: :unprocessable_entity }
        end
      end
    end
    

    然后添加一个ujs文件以便即时进行更改(这会做两件事,添加新注释并清空表单)。

    # app/views/comments/create.js.erb
    $('#comments').append("<%= escape_javascript(render partial: '/comments/comment', locals: { comment: @comment } ) %>"); 
    $('form.new_comment').find("input#comment_body").val('');
    

    另请注意::

    • 我使用@new_comment,因此在呈现新创建的评论时不会受到干扰
    • 您需要在2个地方添加@new_comment,首先在帖子中显示操作,并在评论中创建操作