8
votes

Deux colonnes ne doivent pas être égales dans des rails

Je crée un réseau social dans les rails et j'ai un modèle comme celui-ci:

def addfriend
    if params[:id]
        @friendship = Friendship.new()
        @friendship.user1_id = session[:user]
        @friendship.user2_id = params[:id]
        respond_to do |format|
            if @friendship.save
                format.html { redirect_to "/" } # Yes, SO users, I will fix this redirect later and it is not important for now.
                format.xml  { render :xml => @friendship, :status => :created }
            else
                format.html { redirect_to "/" }
                format.xml  { render :xml => @friendship.errors, :status => :unprocessable_entity }
            end
        end
    end
end


2 commentaires

FYI Dans votre migration, vous pouvez simplement utiliser T.TIMESTAMP au lieu de T.DateTime "Created_AT" et T.DateTime "mise à jour_at".


@Beerlington: Je viens de copier une partie de dB / schema.rb


3 Réponses :


4
votes
if :user1_id == :user2_id
That's always gonna be false - you're comparing the symbols. It's the same as writing if "user1_id" == "user2_id".You should write it as if user1_id == user2_id to compare the values of the columns.

0 commentaires

14
votes

Essayez-le comme ceci:

class Friendship < ActiveRecord::Base
  validate :cannot_add_self

  private

  def cannot_add_self
    errors.add(:user2_id, 'You cannot add yourself as a friend.') if user1_id == user2_id
  end
end


1 commentaires

Pour les rails 3 besoin d'utiliser erros [: base] << "erreur d'erreur" car Add_To_Base a été supprimé des rails3. Voir Stackoverflow.com/Questtions/10284286/...



0
votes

plus amusant: xxx


0 commentaires