【问题标题】:Validation condition on friendships in Rails 3?Rails 3中友谊的验证条件?
【发布时间】:2012-07-09 03:40:24
【问题描述】:

我正在编写我的社交网络。我使用设计作为身份验证系统。我在 railscasts 中使用了自指关联。我想解决我的小问题,我让用户看到其他人的个人资料并使用链接添加朋友。但是,如果您是朋友,则添加到朋友会再次显示。我问了类似的问题,但现在我无法做到。

我的友谊模型:

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

【问题讨论】:

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


【解决方案1】:

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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-08-22
  • 1970-01-01
  • 2011-07-08
  • 2012-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
相关资源
最近更新 更多