2012-07-09 87 views
0

我在寫我的社交網絡。我使用設計作爲認證系統。我在railscasts中使用了自我參照協會。我想解決我的小問題,我讓用戶看到其他配置文件並使用鏈接添加好友。但是,如果你是朋友,添加到朋友再次顯示。我問了類似的問題,但自從現在我無法做到。Rails 3中友誼的驗證條件?

我的友誼模式:

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(用戶)

<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?條件添加朋友鏈接。

+0

有一個非常類似的問題[http://stackoverflow.com/questions/11294147/newbie-getting-mutual-likes-and-only-if-他們是 - 互動與活動記錄/ 11299435#11299435] – HargrimmTheBleak 2012-07-10 04:41:14

回答

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) ... 
+0

'存在?'已經定義在'AR :: Base'中(http://apidock.com/rails/ActiveResource/Base/exists%3F/類),我會重命名方法(除非這真的是你的意圖)。 – HargrimmTheBleak 2012-07-10 04:36:48

+0

修正了,謝謝。 – deefour 2012-07-10 04:38:39