简体   繁体   中英

Rails Create new active record with association value passed in params

I have 2 rails models which look like this

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


In my controller, I am using the code below to create a new Physician record with a bunch of state licenses but for some reason, the state licenses I pass to the create function never make it to the Physician model

 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

What am I doing wrong?

Try changing this:

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

to this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM