ruby on rails-多模型保存,如何包装事务和报告错误



我有一个注册表单模型,它接受用户在注册过程中输入的信息:

class RegForm
    include ActiveModel::Model
    include ActiveModel::Validations
    attr_accessor :company_name, :email, :password
    validates_presence_of # ...
end

在这个注册过程中,我有多个模型需要创建,我不知道如何正确显示错误消息,以及如何将模型错误消息冒泡回UI。

if @reg_form.valid?
   account = Account.create!(@reg_form)
else 
...

创建帐户!看起来像:

def self.create!(reg_form)
  account = Account.create_from_reg!(reg_form)
  location = location.create_from_reg!(account, reg_form)
  ..
  ..
  account.location = location
  ..
  account.save!
  account
end
  1. 所以我很困惑如何显示所有这些正在保存的模型的错误消息
  2. 如果reg_form没有所有其他模型的正确数据,如何显示验证或验证失败
  3. 如何确保这被封装在事务中,这样如果任何模型在注册过程中未能保存,我就不会保存任何东西

让我们从头开始。

我们希望我们的注册表单对象具有与任何其他ActiveRecord模型相同的API:

// view.html
<%= form_for(@book) do |f| %>
<% end %>
# controller.rb
def create
  @book = Book.new(book_params)
  if @book.save
    redirect_to @book, notice: 'Book was successfully created.'
  else
    render :new
  end
end

为此,我们创建以下对象:

class RegForm
  include ActiveModel::Model
  attr_accessor :company_name, :email, :password
  def save
    # Save Location and Account here
  end
end

现在,通过包含ActiveModel::Model,我们的RegForm获得了大量功能,包括显示错误和验证属性(是的,没有必要包含ActiveModel::Validations)。在下一步中,我们添加了一些验证:

validates :email, :password, presence: true

我们更改save,使其运行这些验证:

def save
  validate
  # Save Location and Account here
end

如果所有验证都通过,则validate返回true,否则返回false

validate还会向@reg_form添加错误(所有ActiveRecord模型都有一个errors散列,当验证失败时会填充该散列)。这意味着在我们看来,我们可以做任何一件事:

@reg_form.errors.messages
#=> { email: ["can't be blank"], password: ["can't be blank"] }
@reg_form.errors.full_messages
#=> ["Email can't be blank", "Password can't be blank"]
@reg_form.errors[:email]
#=> ["can't be blank"]
@reg_form.errors.full_messages_for(:email)
#=> ["Email can't be blank"]

同时,我们的RegistrationsController应该是这样的:

def create
  @reg_form = RegForm.new(reg_params)
  if @reg_form.save
    redirect_to @reg_form, notice: 'Registration was successful'
  else
    render :new
  end
end

我们可以清楚地看到,当@reg_form.save返回false时,new视图被重新渲染。

最后,我们更改了save,以便我们的模型save调用被封装在事务中:

def save
  if valid?
    ActiveRecord::Base.transaction do
      location = Location.create!(location_params)
      account = location.create_account!(account_params)
    end
    true
  end
rescue ActiveRecord::StatementInvalid => e
  # Handle database exceptions not covered by validations.
  # e.message and e.cause.message can help you figure out what happened
end

值得注意的要点:

  1. 使用CCD_ 17代替CCD_。只有在引发异常的情况下,事务才会回滚(带有bang的方法通常会这样做)。

  2. CCD_ 19只是CCD_ 20的别名。为了避免所有这些缩进,我们可以在save方法的顶部使用一个保护:

    return if invalid?
    
  3. 我们可以通过执行以下操作将数据库异常(如电子邮件唯一性约束)转化为错误:

    rescue ActiveRecord::RecordNotUnique
      errors.add(:email, :taken)
    end
    
  4. 我们可以使用符号:base:添加与属性没有直接关联的错误

    errors.add(:base, 'Company and Email do not match')
    

我认为事务和错误处理将帮助您解决问题。

def save_or_rescue
  ActiveRecord::Base.transaction do
    account = Account.create_from_reg!(reg_form)
    location = location.create_from_reg!(account, reg_form)
    ...
  end
rescue ActiveRecord::RecordInvalid => exception
  puts exception
end

最新更新