Rails 3中友情的验证条件?

时间:2012-07-09 17:34:51

标签: ruby-on-rails conditional rails-activerecord

我正在写我的社交网络。我使用devise作为身份验证系统。我在轨道广播中使用了自引用协会。我想解决我的小问题,我让用户看到其他人的个人资料,并使用链接添加朋友。但如果你是朋友添加到朋友确实再次显示。我问了类似的问题,但从现在开始我无法做到。

我的友谊模特:

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?条件。

1 个答案:

答案 0 :(得分: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) ...