Thursday, 15 April 2010

validation - Callback not working as expected in Rails 3.2 -



validation - Callback not working as expected in Rails 3.2 -

i have case user can request invitation, if don't have request in system. if request invitation, invitation.sender_id set "0", , if received invitation user, invitation.sender_id set current_user.id, >0.

the invitation.rb model has before_create :recipient_has_requested , callback is:

def recipient_has_requested if invitation.exists?(recipient_email: :recipient_email, sender_id: 0) errors.add :recipient_email, 'an invitation has been sent email address.' end end

when check sql in log, see:

invitation exists (0.0ms) select 1 1 "invitations" "invitations"."recipient_email" = 'recipient_email' , "invitations"."sender_id" = 0 limit 1

which understand should returning 'true' callback, preventing new invitation beingness saved. however, glance @ database shows have multiple requests invitation, same email address, , invitation.sender_id = 0.

i'm new this, help appreciated. why callback returning unexpected result?

==edit==

i think logic reversed here. callback finding record matching criteria, , hence returning true.

can take @ logic , tell me how write returns false?

ok, after bit more google-fu, came across couple of similar cases here in sof.

basically, had logic wrong. constructed callback logic true. changed validation scope , worked.

here final snipit:

validates :recipient_email, uniqueness: { scope: :sender_id }

ruby-on-rails-3 validation callback

No comments:

Post a Comment