我有使用Devise生成的用户模型。此用户模型有两种类型(买方或卖方)使用多态关联创建。
class Buyer < ActiveRecord::Base
has_one :user, as: :owner, dependent: :destroy
accepts_nested_attributes_for :user
validates_presence_of :user
validates_associated :user
class User < ActiveRecord::Base
after_commit :transaction_success
after_rollback :transaction_failed
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
belongs_to :owner, polymorphic: true
validates :email, presence: true
validates :first_name, presence: true
private
def transaction_success
logger.info "Transfer succeed for Account #{self.to_param}"
end
def transaction_failed
logger.warn "Transfer failed for Account #{self.to_param}"
end
端 当用户注册时,他从特定的注册链接(/ buyer / new或/ seller / new)执行,从控制器调用create方法:
def create
@buyer = Buyer.new(buyer_params)
@user = User.new(user_params)
respond_to do |format|
begin
User.transaction do
@buyer.save
@user.owner_id = @buyer.id
@user.owner_type = "Buyer"
@user.save
end
format.html { sign_in_and_redirect @user, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: @user }
rescue ActiveRecord::Rollback
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
问题在于,有时交易失败但是在没有用户的情况下保存了买方。此外,设计验证或我在用户模型中包含的任何验证都没有任何区别,允许用户在没有任何电子邮件,密码等的情况下创建。
如何修复事务并确保验证有效?