如何将新创建的id提交到关联的表/模型中?

时间:2013-10-24 02:28:59

标签: ruby-on-rails ruby-on-rails-4 nested-attributes

我有两种模式:

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 %>    

db migration:

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

2 个答案:

答案 0 :(得分:1)

在你的控制器中,你需要用“新”方法建立关系。

看一下这个例子:

  # 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

它将为新地址创建新的联系人和字段。这称为嵌套表单,因此如果您需要进一步挖掘。

答案 1 :(得分:0)

问题是我最初在我的Clients表中有'copay'字段(并且在模型中有参考验证它),当我从Clients和InsuranceProviders中删除列时,我忘了摆脱客户模型中的参考。这混淆了我和我自己的地狱。