Rails 使用在参数中传递的关联值创建新的活动记录

Rails Create new active record with association value passed in params

我有 2 个 rails 模型,看起来像这样

class Physician < UserProfile
   has_many :state_licenses, inverse_of: :physician, autosave: true, dependent: :destroy
   validates :state_licenses, :length => { :minimum => 1, message: "Please select at-least one state license"}
class StateLicense < ApplicationRecord
  include RailsAdminPhysicianDependencyConcern

  belongs_to :physician, inverse_of: :state_licenses
  belongs_to :state, optional: true

  attr_accessor :client_id

  validates :state, presence: { message: I18n.t("errors.choose_one", field: 'state') }
  #validates :license_number, presence: { message: I18n.t("errors.blank") }

  def name
    return "" unless state
    "#{state.try(:name)}"
  end

end


在我的控制器中,我正在使用下面的代码创建一个带有一堆州许可证的新医师记录,但出于某种原因,我传递给创建函数的州许可证从未进入医师模型

 def create
    physician = nil
    ActiveRecord::Base.transaction do

      state_licenses = params["state_licenses"]


      state_licenses_For_Association = []

      if (state_licenses != nil)
        state_licenses.each do |state_license|
          sl = {}
          sl[:state_id] = state_license
          state_licenses_For_Association.push(sl)
        end
      end


      physician = Physician.create(params.permit(:first_name, :last_name, :title, :residency_board_status, :residency_specialty_id, :state_licenses => state_licenses_For_Association))
      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

我做错了什么?

尝试改变这个:

physician = Physician.create(params.permit(:first_name, :last_name, :title, :residency_board_status, :residency_specialty_id, :state_licenses => state_licenses_For_Association))

对此:

physician = Physician.create(params.permit(:first_name, :last_name, :title, :residency_board_status, :residency_specialty_id).merge(state_licenses: state_licenses_For_Association)) # note the .merge call