필자는 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 post 및 AJAX feed update on post 및 How to update feed using ajax in Rails 4.0
내가 놓친 게 있을지 모르지만, 레일스에서 정말 새로운 경험이 되었기 때문에 자비를 베풀어주기를 바랍니다.
시간을내어 도와 주셔서 감사합니다.
.js.erb – niceman
루트로 리디렉션하려면 create.js.erb 내부에 window.location.href를 지정하는 것이 좋을 것이라고 생각합니다. – niceman