をリフレッシュするために失敗しているが、マイケル・ハートル氏の著書からのガイドを変更することで、自分のアプリケーションにフィード:https://www.railstutorial.org/book/following_usersAJAXフォームIは、Twitter風を追加しようとしている正しく提出するが、フォーム
有効にする必要があり、「追跡」ボタンがあります押されたときに「unfollow」に、またはその逆になります。フォームが正常に送信されています(ページをリフレッシュすると、ボタンが正しいバージョンに変更され、リレーションシップがデータベースに作成されます)が、ページが完全に更新されずに正しいバージョンに変更されません。
_follow_form.html.erb(部分は、メインビュー・ページによって読み込ま)
<div id="follow_form">
<% if current_user.following?(@restaurant) %>
<%= render 'restaurants/unfollow' %>
<% else %>
<%= render 'restaurants/follow' %>
<% end %>
</div>
_follow.html.erb(ボタンに従う)
<%= bootstrap_form_for(current_user.active_relationships.build, remote: true) do |f| %>
<div><%= hidden_field_tag :followed_id, @restaurant.id %></div>
<%= f.submit "Follow", class: "btn btn-primary" %>
<% end %>
_unfollow.html.erb(フォローボタン)
<%= bootstrap_form_for(current_user.active_relationships.find_by(followed_id: @restaurant.id),
html: { method: :delete }, remote: true) do |f| %>
<%= f.submit "Unfollow", class: "btn" %>
<% end %>
関連コントローラ
class RelationshipsController < ApplicationController
before_action :authenticate_user!
def create
restaurant = Restaurant.find(params[:followed_id])
current_user.follow(restaurant)
respond_to do |format|
format.html { redirect_to @restaurant }
format.js
end
end
def destroy
restaurant = Relationship.find(params[:id]).followed
current_user.unfollow(restaurant)
respond_to do |format|
format.html { redirect_to @restaurant }
format.js
end
end
end
create.js.erb
$("#follow_form").html("<%= escape_javascript(render('restaurants/unfollow')) %>");
$("#followers").html('<%= @restaurant.followers.count %>');
destroy.js.erb
$("#follow_form").html("<%= escape_javascript(render('restaurants/follow')) %>");
$("#followers").html('<%= @restaurant.followers.count %>');
は、ここで私はクロームに応じて取得していますエラーです:
NoMethodError in Relationships#destroy
Showing /home/ubuntu/workspace/suburblia/app/views/restaurants/_follow.html.erb where line #2 raised:
undefined method `id' for nil:NilClass
Trace of template inclusion: app/views/relationships/destroy.js.erb
Rails.root: /home/ubuntu/workspace/suburblia
レストランはローカル変数です。@restaurantはインスタンス変数です。インスタンス変数はビューで使用できます。 –