2016-06-28 68 views
1

我經歷了Michael Hartl的Rails教程書,我想使用Ajax進行自動饋送刷新,創建微博和刪除微博。Rails教程部分刷新

據我所知,我只需要在正確的部分內部的形式中指定remote:true參數,並在適當的方法內響應js。不過,當我嘗試使用創建動作完成部分刷新時,我得到一個奇怪的NoMethodError,指示我的@feed_items是一個零對象。

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 post and AJAX feed update on post and How to update feed using ajax in Rails 4.0

我可能錯過了一些東西,但由於我對Rails非常陌生,所以我希望你會很仁慈。

感謝您的時間,幫助和歡呼。

+0

你家的行動將不會在Ajax請求創建行動解僱了,因爲你沒有任何形式的重定向的內部創建.js.erb – niceman

+0

如果你想重定向到根目錄,我認爲在create.js.erb中分配window.location.href是你想要的 – niceman

回答

0

好吧,這可能有點不好,但我設法通過在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)