2012-07-09 43 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