Rails教程部分刷新

时间:2016-06-28 10:46:22

标签: ruby-on-rails ajax

我浏览了Michael Hartl的Rails教程书,我想使用Ajax进行自动提要刷新,创建微博和删除微博。

据我了解,我只需要在正确的partial内部的表单中指定remote:true参数,并在适当的方法内响应js。

然而,当我尝试使用create动作完成部分刷新时,我得到一个奇怪的NoMethodError,表明我的@feed_items是一个nil对象。

Started POST "/microposts" for 77.70.8.167 at 2016-06-28 10:21:32 +0000
Processing by MicropostsController#create as JS
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"qJHp9flp+EV+cxdeF69L8eSzC1fMsjr+mi57f3u3z2Y/fJI9dl1to9t4jlrX4g2uhIP67FiwvjwL7SP2Hmc4fw==", "micropost"=>{"content"=>"dsdsds"}, "commit"=>"Post"}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
   (0.1ms)  begin transaction
  SQL (0.3ms)  INSERT INTO "microposts" ("content", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["content", "dsdsds"], ["user_id", 1], ["created_at", "2016-06-28 10:21:32.797365"], ["updated_at", "2016-06-28 10:21:32.797365"]]
   (11.1ms)  commit transaction
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@NilClass
  Rendered shared/_feed.html.erb (7.7ms)
  Rendered microposts/create.js.erb (11.5ms)
Completed 500 Internal Server Error in 43ms (ActiveRecord: 11.7ms)

NoMethodError (undefined method `any?' for nil:NilClass):
  app/views/shared/_feed.html.erb:3:in `_app_views_shared__feed_html_erb___1168566426182367941_69986820092480'
  app/views/microposts/create.js.erb:1:in `_app_views_microposts_create_js_erb__3336806296105309297_69986601152860'
  app/controllers/microposts_controller.rb:9:in `create'

这是我的_micropost.html.erb部分:

<%= form_for(@micropost, remote: true) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <div class="field">
    <%= f.text_area :content, placeholder: "Compose new micropost..." %>
  </div>
  <%= f.submit "Post", class: "btn btn-primary" %>
  <span class="picture">
    <%= f.file_field :picture, accept: 'image/jpeg, image/gif, image/png' %>
  </span>
<% end %>

<script type="text/javascript">
  $('#micropost_picture').bind('change', function(){
    size_in_megabytes = this.files[0].size/1024/1024;
    if (size_in_megabytes > 5) {
      alert('Maximum file size is 5MB. Please chose a smaller file.')
    }
  })
</script>

Create.js.erb:

$(".ajaxreloadposts").html("<%= escape_javascript(render('shared/feed')) %>");

_feed.html.erb:

<% if @feed_items.any? %>
  <ol class="microposts">
    <%= render @feed_items %>
  </ol>
  <%= will_paginate @feed_items %>
<% end %>

创建行动:

  def create
    @micropost = current_user.microposts.build(micropost_params)
    if @micropost.save!
      # flash[:success] = "Micropost created!"
      respond_to do |format|
        format.html { redirect_to root_path }
        format.js
      end
    else
      @feed_items = []
      render 'static_pages/home'
    end
  end

_home_logged_in.html.erb:

<div class="row">
  <aside class="col-md-4">
    <section class="user_info">
      <%= render 'shared/user_info' %>
    </section>
    <section class="stats">
      <%= render 'shared/stats' %>
    </section>
    <section class="micropost_form">
      <%= render 'shared/micropost_form' %>
    </section>
  </aside>
  <div class="col-md-8">
    <h3>Where are your buddies right now?</h3>
    <%= render 'shared/gmaps' %>
  </div>
  <div class="col-md-8">
    <h3>Micropost Feed</h3>
      <span class="ajaxreloadposts">
        <%= render 'shared/feed' %>
      </span>
  </div>
</div>

最后,我想,我的static_pages_controller的相关部分:

def home
    if logged_in?
      @micropost = current_user.microposts.build
      @feed_items = current_user.feed.paginate(page: params[:page])
      @gmaps_users = current_user.gmaps_feed
      @hash = Gmaps4rails.build_markers(@gmaps_users) do |spot, marker|
        marker.lat spot.lat
        marker.lng spot.lng
        marker.infowindow spot.user.name
      end
      if !current_user.checkin.nil?
        @user_lat = current_user.checkin.lat
        @user_lng = current_user.checkin.lng
      end
    end
  end

我尝试了这些资源,但徒劳无功: AJAX to update micropost vote up/down partial only refreshes the most recent postAJAX feed update on postHow to update feed using ajax in Rails 4.0

我可能错过了一些东西,但由于我是Rails的新手,我希望你会怜悯。

感谢您的时间,帮助和欢呼。

1 个答案:

答案 0 :(得分:0)

好吧,它可能有点像noobish,但我设法通过在create和destroy方法中插入一个名为@feed_items的实例变量来解决问题。

  def create
    @feed_items = current_user.feed.paginate(page: params[:page])
    @micropost = current_user.microposts.build(micropost_params)
    if @micropost.save!
      # flash[:success] = "Micropost created!"
      respond_to do |format|
        format.html { redirect_to root_path }
        format.js
      end
    else
      @feed_items = []
      render 'static_pages/home'
    end
  end

  def destroy
    @micropost.destroy
    @feed_items = current_user.feed.paginate(page: params[:page])
    # flash[:success] = "Micropost deleted!"
    respond_to do |format|
      format.html { redirect_to request.referrer || root_url }
      format.js
    end
  end

这里是微博创建和删除的轨道输出:

Started POST "/microposts" for 77.70.8.167 at 2016-06-28 12:20:56 +0000
Processing by MicropostsController#create as JS
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"wd7XeH4MYDINH2+PrDy8perRJ77VKTwjZ82tsHdESbNWM6yw8Tj11KgU9otscfr6iuHWBUEruOH2DvU5EpS+qg==", "micropost"=>{"content"=>"workworkwork"}, "commit"=>"Post"}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
   (0.1ms)  begin transaction
  SQL (0.3ms)  INSERT INTO "microposts" ("content", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["content", "workworkwork"], ["user_id", 1], ["created_at", "2016-06-28 12:20:56.699428"], ["updated_at", "2016-06-28 12:20:56.699428"]]
   (11.0ms)  commit transaction
   (3.5ms)  SELECT COUNT(*) FROM "microposts" WHERE (user_id IN (SELECT followed_id FROM relationships
                     WHERE follower_id = 1)
                     OR user_id = 1)
  Micropost Load (1.2ms)  SELECT  "microposts".* FROM "microposts" WHERE (user_id IN (SELECT followed_id FROM relationships
                     WHERE follower_id = 1)
                     OR user_id = 1)  ORDER BY "microposts"."created_at" DESC LIMIT 30 OFFSET 0
  CACHE...
  Rendered microposts/_micropost.html.erb (43.1ms)
  Rendered shared/_feed.html.erb (60.3ms)
  Rendered microposts/create.js.erb (65.5ms)
Completed 200 OK in 99ms (Views: 76.4ms | ActiveRecord: 17.6ms)


Started DELETE "/microposts/348" for 77.70.8.167 at 2016-06-28 12:20:59 +0000
Processing by MicropostsController#destroy as JS
  Parameters: {"id"=>"348"}
  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 1]]
  Micropost Load (0.1ms)  SELECT  "microposts".* FROM "microposts" WHERE "microposts"."user_id" = ? AND "microposts"."id" = ?  ORDER BY "microposts"."created_at" DESC LIMIT 1  [["user_id", 1], ["id", 348]]
   (0.1ms)  begin transaction
  SQL (0.4ms)  DELETE FROM "microposts" WHERE "microposts"."id" = ?  [["id", 348]]
   (9.5ms)  commit transaction
   (0.5ms)  SELECT COUNT(*) FROM "microposts" WHERE (user_id IN (SELECT followed_id FROM relationships
                     WHERE follower_id = 1)
                     OR user_id = 1)
  Micropost Load (1.3ms)  SELECT  "microposts".* FROM "microposts" WHERE (user_id IN (SELECT followed_id FROM relationships
                     WHERE follower_id = 1)
                     OR user_id = 1)  ORDER BY "microposts"."created_at" DESC LIMIT 30 OFFSET 0
  CACHE...
  Rendered microposts/_micropost.html.erb (50.9ms)
  Rendered shared/_feed.html.erb (65.8ms)
  Rendered microposts/destroy.js.erb (71.0ms)
Completed 200 OK in 99ms (Views: 75.6ms | ActiveRecord: 18.9ms)