据我所知,验证应该在回调之前运行。不过,我得到的行为表明并非如此。具体来说,我有:
class User::GroupInvitation < ActiveRecord::Base
validate :user_can_be_invited
before_create :find_or_create_membership
private
def user_can_be_invited
user_membership = User::Membership.where(:group_id => self.group_id, :user_id => self.invitee_id).first
if user_membership.present?
case user_membership.status
when "invited"
errors[:base] << I18n.t("user.group_invitations.create.this_user_is_already_invited")
end
end
end
def find_or_create_membership
user_membership = User::Membership.where(:group_id => self.group_id, :user_id => self.invitee_id).first_or_create(:status => "invited")
user_membership.update_column(:status, "invited") unless user_membership.new_record?
self.user_membership_id = user_membership.id
end
end
测试此代码时,我始终收到错误“该用户已被邀请”,即使该用户之前没有被邀请过。我最好的猜测是,这是因为find_or_create_membership
首先运行,因此设置status
为invited
. 关于发生了什么或如何解决这种情况的任何想法?