【问题标题】:Rails Create new active record with association value passed in paramsRails 使用参数中传递的关联值创建新的活动记录
【发布时间】:2019-08-31 10:44:56
【问题描述】:

我有 2 个类似这样的导轨模型

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


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

 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

我做错了什么?

【问题讨论】:

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


    【解决方案1】:

    尝试改变这个:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多