現在ユーザーが他のユーザーをSNSのようにフォローする機能を作成しています。
View
<% if current_user.following?(@account) %>
<%= link_to 'フォロー解除', user_account_path(@account), method: :delete, remote: true %>
<% else %>
<%= link_to 'フォローする', user_account_path(@account), method: :put, remote: true %>
<% end %>
出力されるAタグ
<a data-remote="true" rel="nofollow" data-method="delete" href="/user/account/1">
フォロー中
</a>
<a data-remote="true" rel="nofollow" data-method="put" href="/user/account/1">
フォローする
</a>
Controller
def update
if current_user.follow(account)
render 'follow.js.erb' and return
else
render 'error.js.erb' and return
end
end
def destroy
if current_user.unfollow(account)
render 'unfollow.js.erb' and return
else
render 'error.js.erb' and return
end
end
上記のようなコードで、link_toを押すとフォロー機能は動くものの、同時にページ遷移がしてしまい原因がわからず困っています。
こちらが一部切り取っていますが、ログです。
適切に PUT
アクションができ、レンダリングしたい user/accounts/follow.js.erb
もレンダリングされているのですが、
その後に Started GET "/user/account/1"
のリクエストも走ってしまっているためページ遷移がしてしまいます。
Started PUT "/user/account/1" for 127.0.0.1 at 2020-09-10 17:16:34 +0900
Processing by **Controller#update as HTML
Rendering user/accounts/follow.js.erb
Rendered user/partial/_action_follow.html.erb (Duration: 6.6ms | Allocations: 2080)
Rendered user/accounts/follow.js.erb (Duration: 7.5ms | Allocations: 2647)
Completed 200 OK in 90ms (Views: 5.7ms | ActiveRecord: 42.9ms | Allocations: 19176)
Started GET "/user/account/1" for 127.0.0.1 at 2020-09-10 17:16:34 +0900
Processing by **#not_found as HTML
↳ config/initializers/arproxy.rb:10:in `execute'
Completed 404 Not Found in 46ms (ActiveRecord: 10.5ms | Allocations: 5494)
アドバイスをいただければと思います。よろしくおねがいします。
追記
follow.js.erb
$('.js-follow').html("<%= j render 'user/partial/action_follow', account: @account %>");
_action_follow.html.erb(フォローするボタンのあるビューのファイル)
<% if logged_in? %>
<% if current_user.following?(account) %>
<div class="btn-unfollow">
<%= link_to user_user_account_path(account), method: :delete, remote: true do %>
フォロー中
<% end %>
</div>
<% else %>
<div class="btn-follow">
<%= link_to user_user_account_path(account), method: :put, remote: true do %>
フォローする<%= image_tag "icon-follow.svg", alt: '' %>
<% end %>
</div>
<% end %>
<% else %>
<%# Note: 非ログイン時は、ログイン画面に誘導する %>
<div class="btn-follow">
<%= link_to user_login_path, method: :get do %>
フォローする<%= image_tag "icon-follow.svg", alt: '' %>
<% end %>
</div>
<% end %>
一旦ですが、link_toをbutton_toに変えてControllerでは if request.xhr?と ajaxリクエストのときのみアクションするように変更することで動作自体は期待した動作になりました。