現在、Facebookのような友達申請機能を作成したいと考えております。
ツイッターのようなフォロー、フォロワーのような関係は作成できたのですが、
友達になる(申請) => 申請待ち => 承認(相手) =>友達関係
という手順が上手く作成できません。
お手数おかけしますが、
アドバイス宜しくお願いします。
私的には、
このように申請する側とされる側の外部キーと申請状態を表すstatusを持ったRlationshipというテーブルを作成しました。
class CreateRelationships < ActiveRecord::Migration def change create_table :relationships do |t| t.references :follow, index: true t.references :followed, index: true t.string :status t.timestamps null: false t.index [:follow_id , :followed_id] , unique: true end end end
そして、
両方の外部キーにはユーザのidが入るので、
Relationshipモデルを
class Relationship < ActiveRecord::Base belongs_to :follower, class_name: "User" belongs_to :followed, class_name: "User" end
ユーザモデルはこうです。
class User < ActiveRecord::Base has_one :member has_many :microposts has_many :comments has_many :following_relationships, class_name: "Relationship" , foreign_key: "follow_id" , dependent: :destroy has_many :following_users , through: :following_relationships , source: :followed has_many :follower_relationships, class_name: "Relationship" , foreign_key: "followed_id",dependent: :destroy has_many :follower_users, through: :follower_relationships , source: :follow has_secure_password accepts_nested_attributes_for :member # 他のユーザーをフォローする def follow(other_user ,status) following_relationships.create(followed_id: other_user.id , status: status.status) end # フォローしているユーザーをアンフォローする def unfollow(other_user) following_relationships.find_by(followed_id: other_user.id).destroy end # あるユーザーをフォローしているかどうか? def following?(other_user) following_users.include?(other_user) end end
そして、
relationshipsコントローラで、
class RelationshipsController < ApplicationController before_action :logged_in_user def create @user = User.find(params[:followed_id]) @status = Relationship.new(relationship_params) current_user.follow(@user , @status) end def destroy @user = current_user.following_relationships.find(params[:id]).followed current_user.unfollow(@user) end def edit end private def relationship_params params.require(:relationship).permit(:status) end end
友達になるがこうです
<%= form_for(current_user.following_relationships.build, remote: true) do |f| %> <div><%= hidden_field_tag :followed_id, @user.id %></div> <%= f.submit "Follow", class: "btn btn-primary" %> <% end %>
友達解除がこうです。
<%= form_for(current_user.following_relationships.find_by(followed_id: @user.id), html: { method: :delete }, remote: true) do |f| %> <%= f.submit "Unfollow", class: "btn" %> <% end %>
友達申請等はAjaxを使用しているため、
友達、解除のAjaxの記述はこうです。
create $("#follow_form").html("<%= escape_javascript(render('users/unfollow')) %>"); $("#followers").html('<%= @user.follower_users.count %>'); destroy $("#follow_form").html("<%= escape_javascript(render('users/follow')) %>"); $("#followers").html('<%= @user.follower_users.count %>');
あなたの回答
tips
プレビュー