验证唯一性方法仅遵循一次

时间:2016-03-27 10:04:24

标签: ruby-on-rails validation devise

我创建了一个与用户(Devise)完全相同的系统。 我跟随了Ryan Bates Rails演员http://railscasts.com/episodes/163-self-referential-association

在此代码中,我们可以多次添加同一个用户,我想在人们添加为朋友时阻止。

例如,当User1添加了User2时,链接将被阻止。 我给你一些代码来理解。

迁移称为FriendShip

class CreateFriendships < ActiveRecord::Migration
  def change
    create_table :friendships do |t|
      t.integer :user_id
      t.integer :friend_id

      t.timestamps null: false
    end
  end
end

用户模型

has_many :friendships
has_many :friends, :through => :friendships

友谊的模型是

belongs_to :user
belongs_to :friend, :class_name => "User"

友谊控制器

class FriendshipsController < ApplicationController
  def create
  @friendship = current_user.friendships.build(:friend_id => params[:friend_id])
    if @friendship.save
      flash[:notice] = "Added friend."
      redirect_to current_user
    else
      flash[:error] = "Unable to add friend."
      redirect_to current_user
    end
  end

def destroy
    @friendship = current_user.friendships.find(params[:id])
    @friendship.destroy
    flash[:notice] = "Removed friendship."
    redirect_to current_user
  end
end

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您可以在控制器中执行以下操作:

...
def create
  if current_user.friendships.where(friend_id: params[:friend_id]).any?
    flash[:error] = "You already have added this user."
    redirect_to current_user
  else
    @friendship = current_user.friendships.build(:friend_id => params[:friend_id])
    if @friendship.save
      flash[:notice] = "Added friend."
      redirect_to current_user
    else
      flash[:error] = "Unable to add friend."
      redirect_to current_user
    end
  end
end
...

在您的观点中,您可以执行以下操作:

...
if current_user.id == user.id
  link_to 'Your Profile', '#!'
elsif current_user.friendships.where(friend_id: user.id).any?
  link_to 'Friends', '#!'
else
  link_to 'Add Friend', path_here
end
...