LoginSignup
5
8

More than 5 years have passed since last update.

rails ajaxでフォロー機能

Posted at

フォロー機能作成までは割愛。
非同期処理のajaxを使ったフォローの実装。
自分用のメモなのでわかりにくいです。

show.html.erb
<%= render 'follow_form' %>


<div class="follow" id = "follow-count">
  <%= render 'follow_count' %>
</div>
_follow_form.html.erb
<% if user_signed_in? %>
<% if @user != current_user %>
<div id="follow_form">
  <% if current_user.following?(@user) %>
   <%= render 'unfollow' %>
  <% else %>
   <%= render 'follow' %>
  <% end %>
</div>
<% end %>
<% end %>

フォローボタンはここでcreateとdestroy両方にidが指定してあります。

_follow.html.erb
<%= form_for(current_user.active_relationships.build, remote: true) do |f| %>
  <%= hidden_field_tag :following_id, @user.id %>
  <%= f.submit "フォローする", class: "follow-btn" %>
<% end %>
_unfollow.html.erb
<%= form_for(current_user.active_relationships.find_by(following_id: @user.id), html: { method: :delete }, remote: true) do |f| %>
  <%= f.submit "フォロー中", class: "unfollow-btn" %>
<% end %>

それぞれにremote: trueを追加。

フォローボタンが押された時に、非同期処理で、フォローボタン⇄アンフォローボタンの表示を変える。

フォローボタンを押すということは、createアクションとdestroyアクションを使うことになる。

relationships_controller.rb
  def create
    @user = User.find(params[:following_id])
    current_user.follow(@user)
    respond_to do |format|
     format.html { redirect_to @user }
     format.js
   end
  end

  def destroy
    @user = Relationship.find(params[:id]).following
    current_user.unfollow(@user)
    respond_to do |format|
     format.html { redirect_to @user }
     format.js
   end
  end

これでcreate.js.erbとdestroy.js.erbファイルを探すようになる。

create.js.erbとdestroy.js.erbの作成

create.js.erb
$("#follow_form").html("<%= escape_javascript(render('users/unfollow')) %>");

$("#follow-count").html("<%= escape_javascript(render('users/follow_count')) %>");

destroy.js.erb
$("#follow_form").html("<%= escape_javascript(render('users/follow')) %>");

$("#follow-count").html("<%= escape_javascript(render('users/follow_count')) %>");

renderは、当然非同期処理後に表示されて欲しいページを指定してあげる。
なので、フォローを非同期処理した後に表示されて欲しいのはunfollowボタンだから、unfollowページにリダイレクト。
逆も同じ。

それで、フォローする、はずすのあとに応じてフォロワー数は変わるはずだから、それも非同期でやりたい。

そこで、もう指定してあるが、createやdestroyボタンを押した時に数を変えたいから、create.js.erbとdestroy.js.erbにもその処理を記述する。
上を参照。

他にももし、フォローボタンを押した時にページのどこか一部を更新したいってなったら、それのパーシャルを作って、create.js.erbとdestroy.js.erbに記述すればよい。

5
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
8