2

据我所知,验证应该在回调之前运行。不过,我得到的行为表明并非如此。具体来说,我有:

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首先运行,因此设置statusinvited. 关于发生了什么或如何解决这种情况的任何想法?

4

2 回答 2

9

find_or_create_membership首先运行

创建时的操作顺序:

before_validation
after_validation
before_save
around_save
before_create
after_create
after_save
于 2013-03-12T20:09:31.903 回答
2

问题实际上源于我的控制器:

invitation = User::GroupInvitation.create(params[:user_group_invitation])
if invitation.valid?
  . . . .
else
  . . . .
end

这导致验证方法在 期间第二次被调用invitation.valid?,当然它会发送错误消息,因为 astatus已经设置了。解决问题很容易。我只是添加了一个:on => :create条件:

validate :user_can_be_invited, :on => :create
于 2013-03-13T16:10:24.360 回答