簡體   English   中英

如何將新創建的ID提交到關聯的表/模型中?

[英]how to submit newly created id into associated table/model?

我有兩個模型:

Clients
 validates :first_name, presence: true
 validates :last_name, presence: true

 #scope :with_current_copay, joins(:insurance_providers).merge(InsuranceProvider.max.group(:client_id))

 has_many :appointments
 has_many :insurance_providers
 accepts_nested_attributes_for :insurance_providers
 belongs_to :users

end

InsuranceProviders (屬於客戶端)。

class InsuranceProvider < ActiveRecord::Base
  #scope :max, -> maximum(:effective_on, :group => 'client_id') 
  belongs_to :client
end

我創建了一個窗體,該窗體創建了一個與InsuranceProvider一起的客戶。

InsuranceProvider有一個名為client_id的列。

填寫表單時,client_id還不存在。 如何將那個client_id放入InsuranceProvider表中?

這是我目前的表格:

<%= simple_form_for(@client) do |f| %>
  <%= f.error_notification %>

  <div class="form-inputs">
    <%= hidden_field_tag :user_id, current_user.id  %>
    <%= f.input :first_name %>
    <%= f.input :last_name %>
    <%= f.fields_for :insurance_providers do |provider| %>
      <%= provider.input :name, label: 'Insurance provider' %>
      <%= provider.input :member_id, label: 'Member ID' %>
      <%= provider.input :copay, as: :integer %>
      <%= provider.input :effective_on, as: :date  %>
    <% end %>
  </div>

  <div class="form-actions">
    <%= f.button :submit %>
  </div>
<% end %>    

數據庫遷移:

class CreateInsuranceProviders < ActiveRecord::Migration
  def change
    create_table :insurance_providers do |t|
      t.integer :client_id
      t.string :name
      t.string :member_id
      t.integer :copay
      t.date :effective_on

      t.timestamps
    end
  end
end

在您的控制器中,您需要使用“ new”方法來建立關系。

看一下這個例子:

  # GET /contacts/new
  # GET /contacts/new.json
  def new
    @contact = Contact.new
    @contact.addresses.build

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @contact }
    end
  end

它將創建一個新的聯系人和一個新地址的字段。 這稱為嵌套表單,因此如果需要進一步挖掘。

問題是我最初在“客戶”表中有“ copay”字段(並在模型中具有驗證它的引用),當我從“客戶”中刪除該列並進入InsuranceProviders時,我忘了擺脫客戶模型。 這使我和自己都陷入困境。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM