nested attributes? thoughts of suicide => true

Yeah, we all know it, Nested Attributes can be a real pain in the ass. Sometimes it’s a struggle to get them working for a even a simple scenario, let alone a complex one.  Nested Attributes come into play when you want to update multiple models in one motion of the ocean (or database in this case). In the words of Michael Bolton, Let’s get to it!

$ rails new NestingRabbits 
$ cd NestingRabbits
# noobs can scaffold and have no shame, however, not recommended on coding challenges from potential employers
$ rails g scaffold Rabbit name:string age:integer on_facebook:boolean
$ rails g model Account rabbit_id:integer account_type:string
$ rake db:migrate
At this point we’ve created our database, one scaffold and one model. The scaffold creates all our views, controller and model. We now want to set up the relationships between our models. Each Rabbit will have one account.
# app/models/rabbit.rb
class Rabbit < ActiveRecord::Base
  has_one :account
  accepts_nested_attributes_for :account
end
# app/models/account.rb
class Account < ActiveRecord::Base
  belongs_to :rabbit
end

Now we can test our relationships and ensure they’re working.

$ rails c
2.1.2 :001 > Rabbit.create(name:"Dan", age: 28, on_facebook:true)
2.1.2 :002 > Account.create(rabbit_id:1,account_type:"nerd")
2.1.2 :003 > Rabbit.last.account => #
Let’s set up our Nested Attributes
# app/controllers/rabbits_controller.rb
class RabbitsController < ApplicationController
  def new
    @rabbit = Rabbit.new
    @rabbit.build_account
  end

  def rabbit_params
    params.require(:rabbit).permit(:name, :age, :on_facebook, account_attributes: [:account_type])
  end
end
# app/views/rabbits/_form.html.erb
<%= form_for(@rabbit) do |f| %>
  <% if @rabbit.errors.any? %>
  

<%= pluralize(@rabbit.errors.count, "error") %> prohibited this rabbit from being saved:

    <% @rabbit.errors.full_messages.each do |message| %>
  • <%= message %>
  • <% end %>
<% end %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :age %>
<%= f.number_field :age %>
<%= f.label :on_facebook %>
<%= f.check_box :on_facebook %>
<%= f.fields_for(:account) do |ac| %>
<%= ac.label :account_type %> <%= ac.text_field :account_type %>
<% end %>
<%= f.submit %>
<% end %>

Now let’s test it out!

$ rails s

Now on your browser go to

http://localhost:3000/rabbits/new

And you should see something similar to this… rabbit-form Fill out the form. And going back into rails c, you should be able to see your latest rabbit with the latest Account! rabbit-completed-form Server Logs rabbit-created-server-logs Rails Console nested-attributes-confirmed As you can see it worked! Woop Woop.

Post Content