Search code examples
ruby-on-railsnested-formsnested-attributesruby-on-rails-5

Form With Nested Attributes Not Saving Rails 5


I have a Client and Office Address Model, I want to create the office address when the client is created, so to do this I have decided to go the nested attribute direction.

When I try to create the Client with the Office Address I get this in the server output, doesn't give me much to go on and not sure how to proceed.

Started POST "/clients" for 127.0.0.1 at 2016-10-26 21:57:06 -0600
Processing by ClientsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"oC4Bwgw8zQrQCGU6RVGXXVwgWGIbOGmyP9gmJYUbyKXVXzgdeRGrp/wMnsmbF6spSeNxTpcHLJx+ZceBKjHxvQ==", "client"=>{"account_id"=>"", "name"=>"Test Client", "client_type"=>"Corp", "client_ident"=>"1234567890", "office_address_attributes"=>{"client_id"=>"", "unit_number"=>"317", "street_number"=>"1717", "street_name"=>"60 st SE", "city"=>"Clagary", "prov_state"=>"Alberta", "postal_zip"=>"T2A7Y7", "country"=>"CA"}}, "commit"=>"Create Client"}
  Account Load (0.1ms)  SELECT  "public"."accounts".* FROM "public"."accounts" WHERE "public"."accounts"."subdomain" = $1 LIMIT $2  [["subdomain", "shawnwilson"], ["LIMIT", 1]]
  User Load (0.4ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
   (0.1ms)  BEGIN
   (0.1ms)  ROLLBACK
  Rendering clients/new.html.erb within layouts/application
  Rendered clients/_form.html.erb (32.8ms)
  Rendered clients/new.html.erb within layouts/application (34.4ms)
  Rendered shared/_signed_in_nav.html.erb (0.7ms)
Completed 200 OK in 109ms (Views: 102.0ms | ActiveRecord: 1.2ms)

So when I create the client I want to associate the client to the account and I want to associate the OfficeAddress to the Client.

My Client Model

class Client < ApplicationRecord
  belongs_to :account, required: true
  has_one :office_address
  validates :office_address, presence: true
  accepts_nested_attributes_for :office_address
end

My Office Address Model

class OfficeAddress < ApplicationRecord
  belongs_to :client, required: true
end

My Client Controller

class ClientsController < ApplicationController
  before_action :set_client, only: [:show, :edit, :update, :destroy]

  # GET /clients
  # GET /clients.json
  def index
    @clients = Client.all
  end

  # GET /clients/1
  # GET /clients/1.json
  def show
  end

  # GET /clients/new
  def new
    @client = Client.new
    @client.build_office_address
  end

  # GET /clients/1/edit
  def edit
  end

  # POST /clients
  # POST /clients.json
  def create
    @client = Client.new(client_params)

    respond_to do |format|
      if @client.save
        format.html { redirect_to @client, notice: 'Client was successfully created.' }
        format.json { render :show, status: :created, location: @client }
      else
        format.html { render :new }
        format.json { render json: @client.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /clients/1
  # PATCH/PUT /clients/1.json
  def update
    respond_to do |format|
      if @client.update(client_params)
        format.html { redirect_to @client, notice: 'Client was successfully updated.' }
        format.json { render :show, status: :ok, location: @client }
      else
        format.html { render :edit }
        format.json { render json: @client.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /clients/1
  # DELETE /clients/1.json
  def destroy
    @client.destroy
    respond_to do |format|
      format.html { redirect_to clients_url, notice: 'Client was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_client
      @client = Client.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def client_params
      params.require(:client).permit(:account_id, :name, :client_type, :client_ident, office_address_attributes: [:unit_number, :street_number, :street_name, :city, :prov_state, :postal_zip, :country, :client_id])
    end
end

My Form

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

  <div class="form-inputs">
    <%= f.input :account_id %>
    <%= f.input :name %>
    <%= f.input :client_type %>
    <%= f.input :client_ident %>
  </div>

  <%= f.fields_for :office_address do |oa| %>
    <%= oa.input :client_id %>
    <%= oa.input :unit_number %>
    <%= oa.input :street_number %>
    <%= oa.input :street_name %>
    <%= oa.input :city %>
    <%= oa.input :prov_state %>
    <%= oa.input :postal_zip %>
    <%= oa.input :country %>
  <% end %>

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

Any assistance here would be much appreciated!

EDIT # 1 - Adds Byebug Errors

(byebug) @client.errors
#<ActiveModel::Errors:0x007fb249813488 @base=#<Client id: nil, account_id: nil, name: "Test Client", client_type: "Corp", client_ident: "1234567890", created_at: nil, updated_at: nil>, @messages={}, @details={}>
(byebug)

Solution

  • If you don't want to turn off validation on related models ( which is not ideal in some cases ) then you should set inverse_of like so

    has_one :office_address, inverse_of: :client
    

    inverse_of is really worth knowing about, this blog explains it well:

    https://www.viget.com/articles/exploring-the-inverse-of-option-on-rails-model-associations