繁体   English   中英

Rails-在视图中提交表单后,AJAX正在加载帖子

[英]Rails - AJAX loading posts after submitting form in view

通过AJAX提交帖子后,我无法使用帖子加载/填充视图。 表单本身正在触发,并将帖子插入数据库。 更清楚地说,提交后,我需要使用JQuery slideDown在帖子下方的容器中加载帖子。 我有一个普通的帖子/共享的帖子/有评论的帖子,以及index动作中的部分渲染。

index.html.erb

<div class="col-md-5">
      <div class="posts-feed-bg">
        <div id="post-index-form">
          <%= render 'posts/form' %>
        </div>
        <div class="post-textarea-bottom-border"></div>
        <div class="post-feed-container" id="posts-items">
          <% @posts.each do |post| %>
              <%= render partial: "posts/#{post.post_type}", locals: {post: post} %>
          <% end %>
        </div>
      </div>
    </div>

create.js.erb

<% if @post.save
      @post = Post.new
%>
    $('#post-index-form').html('<%= escape_javascript(render 'posts/form') %>');
    $('#post-text-area').val('');
    $('#post-items').html('<%= escape_javascript(render 'posts/post') %>');
    $('#post-items').slideDown(350);
    <% end %>

_post.html.erb

  <div class="post-container">
    <%= post.user.username %>
    <%= link_to post.title, post %>
    <%= post.body %>
    </div>

posts_controller.rb

def index
        following_ids = current_user.following_users.map(&:id)
        following_ids << current_user.id
        @posts = Post.where(user_id: following_ids).order('created_at DESC').paginate(page: params[:page])
        @users = User.same_background_focus_as(current_user).paginate :page => params[:page], :per_page => 5
        @post = Post.new
      end

 def create
    @post = current_user.posts.build(post_params)

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render :show, status: :created, location: @post }
        format.js
      else
        format.html { render :new }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

_form.html.erb

<div class="container">
    <%= simple_form_for(@post, id: '', multipart: true, remote: true) do |f| %>
        <%= f.error_notification %>
        <div class="row">
          <div class="col-6 emoji-picker-container post-textarea">
            <%= f.input :body_text, class: 'form-control', label: false, id: 'post-text-area' %>
          </div>
        </div>
        <div class="row">
          <div class="col-md-5">
            <%= f.button :submit, class: 'btn btn-outline-success' %>
          </div>
        </div>
    <% end %>
</div>

提交表单后的服务器日志

Started POST "/posts" for 127.0.0.1 at 2017-08-16 13:25:25 -0400
Processing by PostsController#create as JS
  Parameters: {"utf8"=>"✓", "post"=>{"body_text"=>"AJAX"}, "commit"=>"Create Post"}
  User Load (1.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 4], ["LIMIT", 1]]
   (1.0ms)  BEGIN
  SQL (174.6ms)  INSERT INTO "posts" ("body_text", "user_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"  [["body_text", "AJAX"], ["user_id", 4], ["created_at", "2017-08-16 17:25:26.201583"], ["updated_at", "2017-08-16 17:25:26.201583"]]
   (0.5ms)  COMMIT
  Rendering posts/create.js.erb
   (1.0ms)  BEGIN
   (0.0ms)  COMMIT
  Rendered posts/_form.html.erb (8.0ms) [cache miss]
  Rendered posts/_post.html.erb (1273.9ms)
  Rendered posts/create.js.erb (1366.9ms)
Completed 500 Internal Server Error in 2282ms (ActiveRecord: 178.1ms)



ActionView::Template::Error (undefined local variable or method `post' for #<#<Class:0x18937128>:0x1a9f6688>
Did you mean?  @post
               post_url):
    2:   <div class="media" style="padding-bottom: 2em;">
    3:     <img class="d-flex align-self-start mr-3 purple-rounded rounded" src="http://via.placeholder.com/60x60">
    4:     <div class="media-body post-user-name">
    5:       <h5><%= fa_icon 'user' %> <%= post.user.user_full_name %><%= link_to 'Delete', post_path(post), remote: true, method: :delete, data: {confirm: "You sure?"} if current_user == post.user %> </h5>
    6:       <p><%= post.body_text %> </p>
    7:     </div>
    8:   </div>

app/views/posts/_post.html.erb:5:in `_app_views_posts__post_html_erb__960034244_222460104'
app/views/posts/create.js.erb:9:in `_app_views_posts_create_js_erb__1048995870_223328388'

更改后的新错误

ActionView::Template::Error (undefined method `user_full_name' for nil:NilClass):
    2:   <div class="media" style="padding-bottom: 2em;">
    3:     <img class="d-flex align-self-start mr-3 purple-rounded rounded" src="http://via.placeholder.com/60x60">
    4:     <div class="media-body post-user-name">
    5:       <h5><%= fa_icon 'user' %> <%= post.user.user_full_name %><%= link_to 'Delete', post_path(post), remote: true, method: :delete, data: {confirm: "You sure?"} if current_user == post.user %> </h5>
    6:       <p><%= post.body_text %> </p>
    7:     </div>
    8:   </div>

app/views/posts/_post.html.erb:5:in `_app_views_posts__post_html_erb__960034244_199162944'
app/views/posts/create.js.erb:9:in `_app_views_posts_create_js_erb__1048995870_199612656'

部分视图更改器post.rb的方法

def post_type
    if post_id? && body_text?
      "quote_share"
    elsif post_id?
      "share"
    else
      "post"
    end
  end

问题是您错误地引用了id 您已将id定义为div posts-items ,但是在create.js.erb您使用的post-items是错误的,因此JS无法找到带有post-items的选择器,这就是问题的原因。 将其更改为posts-items应该可以解决您的问题。

#create.js.erb
<% if @post.save
  @post = Post.new
%>
  $('#post-index-form').html('<%= escape_javascript(render 'posts/form') %>');
  $('#post-text-area').val('');
  $('#posts-items').html('<%= escape_javascript(render 'posts/post') %>');
  $('#posts-items').slideDown(350);
<% end %>

另外,这部分代码。

<% if @post.save
  @post = Post.new
%>

好像很奇怪 除非有任何create.js.erb否则我看不出在create.js.erb包含它的任何原因。 所以删除它

#create.js.erb
$('#post-index-form').html('<%= escape_javascript(render 'posts/form') %>');
$('#post-text-area').val('');
$('#posts-items').html('<%= escape_javascript(render 'posts/post') %>');
$('#posts-items').slideDown(350);

更新:

ActionView :: Template :: Error(#<#<Class:0x18937128>:0x1a9f6688>的未定义局部变量或方法`post'

在这种情况下,Rails无法找到_post.html.erb中定义的post变量。 作为局部变量中的局部变量发送。 最终的create.js.erb应该是这样的

#create.js.erb
$('#post-index-form').html('<%= escape_javascript(render 'posts/form') %>');
$('#post-text-area').val('');
$('#posts-items').html('<%= escape_javascript(render 'posts/post', post: @post) %>');
$('#posts-items').slideDown(350);

另外,在form @post Post.new更改为Post.new ,这样它就不会与@postcreate action中发生冲突,并始终为新实例创建一个表单

<%= simple_form_for(Post.new, id: '', multipart: true, remote: true) do |f| %>

ActionView :: Template :: Error(nil:NilClass的未定义方法“ user_full_name”)

该错误是因为该特定帖子没有关联的用户,因此该错误在此行中出现错误<%= post.user.user_full_name %>要快速解决该错误,请使用try方法

<%= post.try(:user).user_full_name %>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM