[英]how to submit newly created id into associated table/model?
I have two models: 我有两个模型:
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
and InsuranceProviders
(which belongs_to clients). 和
InsuranceProviders
(属于客户端)。
class InsuranceProvider < ActiveRecord::Base
#scope :max, -> maximum(:effective_on, :group => 'client_id')
belongs_to :client
end
I've created one form that creates a client along with an InsuranceProvider. 我创建了一个窗体,该窗体创建了一个与InsuranceProvider一起的客户。
InsuranceProvider has a column called client_id. InsuranceProvider有一个名为client_id的列。
The client_id doesn't exist yet when the form is being filled out. 填写表单时,client_id还不存在。 How do I put that client_id into the InsuranceProvider table?
如何将那个client_id放入InsuranceProvider表中?
Here is my form currently: 这是我目前的表格:
<%= 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
In your controller you need to buid the relationships in the "new" method. 在您的控制器中,您需要使用“ new”方法来建立关系。
Take a look at this example: 看一下这个例子:
# 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
It will create a new contact and fields for a new address. 它将创建一个新的联系人和一个新地址的字段。 This is called nested forms, so if you need to digg further.
这称为嵌套表单,因此如果需要进一步挖掘。
The problem was that I originally had the 'copay' field in my Clients table (and had a reference to validating it in the model) and when I removed the column from Clients and into InsuranceProviders, I forgot to get rid of the reference in the Clients Model. 问题是我最初在“客户”表中有“ copay”字段(并在模型中具有验证它的引用),当我从“客户”中删除该列并进入InsuranceProviders时,我忘了摆脱客户模型。 This confused the hell out of both rails and myself.
这使我和自己都陷入困境。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.