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
3 Réponses :
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.
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
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/...
plus amusant:
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