2016-06-28 2 views
1

필자는 Michael Hartl 's Rails Tutorial 서적을 읽었으며 자동 피드 새로 고침, 마이크로 포스트 작성 및 마이크로 포스트 삭제에 Ajax를 사용하고자합니다.레일 튜토리얼 부분 새로 고침

필자가 이해하는 한, 올바른 부분의 내부 양식에 remote : true 매개 변수를 지정하고 적절한 방법으로 js에 응답하면됩니다.

그럼에도 불구하고 내가 만든 작업으로 부분 새로 고침을 시도 할 때 이상한 NoMethodError가 발생하여 내 @feed_items가 nil 개체임을 나타냅니다.

<%= 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 :

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의

<% 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

내가 놓친 게 있을지 모르지만, 레일스에서 ​​정말 새로운 경험이 되었기 때문에 자비를 베풀어주기를 바랍니다.

시간을내어 도와 주셔서 감사합니다.

+0

.js.erb – niceman

+0

루트로 리디렉션하려면 create.js.erb 내부에 window.location.href를 지정하는 것이 좋을 것이라고 생각합니다. – niceman

답변

0

좋아, 조금 멍청 할 수도 있지만 @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 

는 micropost 생성 및 삭제로부터 레일 출력입니다 :

내부 만들려면 리디렉션의 어떤 종류가 없기 때문에 홈 조치는 아약스 요청에 대한 만들 행동에 해고되지 않습니다
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)