Ramy
Ramy

Reputation: 21261

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).

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 has a column called client_id.

The client_id doesn't exist yet when the form is being filled out. How do I put that client_id into the InsuranceProvider table?

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

Upvotes: 0

Views: 47

Answers (2)

Ramy
Ramy

Reputation: 21261

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. This confused the hell out of both rails and myself.

Upvotes: 0

Paulo Fidalgo
Paulo Fidalgo

Reputation: 22311

In your controller you need to buid the relationships in the "new" method.

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.

Upvotes: 1

Related Questions