0

私は自分のソーシャルネットワークを書いています。認証システムとしてdeviseを使用しています。Railscast で Self-Referential Association を使用しました。ユーザーに他のプロファイルを表示し、リンクを使用して友達を追加できるようにするという小さな問題を解決したいと思います。しかし、あなたが友達の場合、友達に追加すると再び表示されます。同様の質問をしましたが、今ではできませんでした。

私の友情モデル:

class Friendship < ActiveRecord::Base
  attr_accessible :friend_id
  belongs_to :user
    belongs_to :friend, :class_name => "User"
    validates :friend, :presence => true, :unless => :friend_is_self

    validates_uniqueness_of :user_id, :scope => [:friend_id]

    def friend_is_self
        user_id == friend_id ? false : true
    end
end

私のユーザー モデル:

....  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

これは私の show.html.erb(user) です

<section>
      <h1><%= @user.username %> </h1>
 <% unless current_user == @user %>
 <%= link_to "Arkadaşlarıma Ekle", friendships_path(:friend_id => @user), :method => :post,class: "btn btn-large btn-primary" %>
    <%end %>
      </section>.

同様の質問で申し訳ありませんが、if friend?友達追加リンクの正しい条件が見つかりません。

4

1 に答える 1

0

Friendshipモデル内のクラス メソッドはどうですか?

class Friendship < ActiveRecord::Base
  # ...

  def self.friendship_exists?(user1, user2)
    Friendship.where("(user_id = ? AND friend_id = ?) OR (user_id = ? AND friend_id = ?)", user1.id, user2.id, user2.id, user1.id).size > 0
  end
end

今、あなたはするlink_to_ifことができます

link_to_unless Friendship.friendship_exists?(current_user, @user) ...
于 2012-07-09T18:05:00.590 に答える