友情の一意性について助けが必要で、友人のリンクに自分のroutes.rbを追加します:
devise_for :users
resources :users, only: [:index, :show] do
resources :friendships, only: [:create, :destroy]
end
私のユーザーモデル:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :username
# attr_accessible :title, :body
has_many :topics
has_many :posts
has_many :friendships
has_many :friends, :through => :friendships
has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"
has_many :inverse_friends, :through => :inverse_friendships, :source => :user
end
私の友情モデル:
class Friendship < ActiveRecord::Base
attr_accessible :friend_id, :user_id
belongs_to :user
belongs_to :friend, :class_name => "User"
end
友情_コントローラー.rb:
class FriendshipsController < ApplicationController
before_filter :authenticate_user!
def create
@friendship = current_user.friendships.build(:friend_id => params[:friend_id])
if @friendship.save
flash[:notice] = "Arkadaşlara eklendi."
redirect_to root_url
else
flash[:error] = "Arkadaşlara Eklenemiyor."
redirect_to root_url
end
end
def destroy
@friendship = current_user.friendships.find(params[:id])
@friendship.destroy
flash[:notice] = "Arkadaşlarımdan kaldırıldı."
redirect_to current_user
end
end
users_controller.rb:
class UsersController < ApplicationController
before_filter :authenticate_user!
def index
@users = User.all
end
def show
@user = User.find(params[:id])
@topics = @user.topics.paginate(page: params[:page])
@friendship = @user.friendships.build(:friend_id => params[:friend_id])
@friendships = @user.friendships.all
end
end
これは私の友達追加リンクです:
<h1>
<%= @user.username %>
</h1>
<%= link_to "Arkadaşlarıma Ekle", friendships_path(:friend_id => @user), :method => :post,class: "btn btn-large btn-primary" %>
また、ユーザーを友達として表示するための正しいパスが見つかりません。
<% for friendship in @friendships %>
<%= link_to friendship.friend.username, '#' %>
(<%= link_to 'Sil', friendship, :method => :delete %>)
<% end %>
誰でも私を助けることができますか?