我有一个用户模型,其中用户有另一个用户的友谊。友谊模型使用类名为 User 的朋友。一切似乎都在正常工作。但是,我认为我只是试图将功能修补在一起,而不是遵循最佳程序。
在我的控制器,友谊控制器中,我有它 current_user 可以添加朋友的地方。但是,我不希望他们添加同一个朋友两次。
user = current_user.id
friend = params[:friend_id]
temp_friendship = Friendship.where('(user_id = ? AND friend_id = ?) OR (user_id = ? AND friend_id = ?)', user,friend,friend,user)
if !temp_friendship.present?
@friendship = current_user.friendships.build(:friend_id => params[:friend_id])
if @friendship.save
redirect_to current_user, :notice => "Added friend."
else
redirect_to current_user, :alert => "Unable to add friend."
end
else
redirect_to current_user, :alert => "Already a friend."
end
这段代码都很好用。但是,似乎我正在对数据库进行不必要的调用。有没有办法优化这个控制器调用,通过模型验证或类似的方法?
我试过这样做,但如果我已经启动了朋友,它只会返回验证错误。如果有人将我添加为朋友(其中friend_id 将是我的用户 ID),它不会引发任何错误。
validates_uniqueness_of :user_id, :scope => :friend_id
validates_uniqueness_of :friend_id, :scope => :user_id