Rails与许多关联创建活动记录

时间:2019-08-31 05:37:58

标签: ruby-on-rails associations rails-activerecord has-many

我有一个Rails模型,该模型具有以下许多关联

class Physician < UserProfile
has_many :state_licenses, inverse_of: :physician, autosave: true, dependent: :destroy
validates_presence_of :state_licenses, :message=>"Please select at-least one state license"

在我的控制者中,我正尝试使用state_licenses如下创建新医师

  def create
    physician = nil
    ActiveRecord::Base.transaction do
      physician = Physician.create(params.permit(:first_name, :last_name, :title, :residency_board_status, :residency_specialty_id))
      logger.debug("in physician create")
      params["user"].merge!({ user_profile_type: Physician.name, user_profile_id: physician.id })

state_licenses = params["state_licenses"]

      if (state_licenses != nil)
        state_licenses.each do |state_license|
          physician.state_licenses.create(physician_id: physician.id, state_id: state_license)
        end
      end

      user_record = nil
      super do |user|
        user_record = user
        user.errors.delete(:user_profile)
        physician.errors.messages.each { |field, messages| messages.each {|message| user.errors.add(field, message)} }
      end
      raise ActiveRecord::Rollback unless user_record.persisted? && physician.persisted?
    end

    AdminNotificationsMailer.physician_signed_up(physician).deliver_now rescue nil
  end

即使我在医师上创建了一堆州许可证,我仍然会收到验证错误,以选择至少一个州许可证。我如何确保在创建医师过程中正确地将医师与州许可证相关联?

0 个答案:

没有答案
相关问题