据我所知,validations are suppose to run before callbacks。不过,我的行为表明不然。具体来说,我有:
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
。关于发生了什么或如何解决这种情况的任何想法?
答案 0 :(得分:8)
find_or_create_membership
正在首先运行
创建时的操作顺序:
before_validation
after_validation
before_save
around_save
before_create
after_create
after_save
答案 1 :(得分:1)
问题实际上源于我的控制器:
invitation = User::GroupInvitation.create(params[:user_group_invitation])
if invitation.valid?
. . . .
else
. . . .
end
这导致验证方法在invitation.valid?
期间第二次被调用,当然它会在已设置status
时发送错误消息。解决问题很容易。我只是添加了一个:on => :create
条件:
validate :user_can_be_invited, :on => :create