I\'m relatively new to rails and finally found the right way to use accepts_nested_attributes_for
.
However, there are some serious resources on the web who
It's much easier to use virtus instead of accepts_nested_attributes_for
than I thought. The most important requirement was to dare to make things that were not covered in any of the tutorials I read yet.
Step by step:
gem 'virtus'
to the Gemfile and ran bundle install
.I wrote a file models/contact.rb and wrote the following code:
class Contact
include Virtus
extend ActiveModel::Naming
include ActiveModel::Conversion
include ActiveModel::Validations
attr_reader :name
attr_reader :number
attribute :name, String
attribute :number, Integer
def persisted?
false
end
def save
if valid?
persist!
true
else
false
end
end
private
def persist!
@person = Person.create!(name: name)
@phones = @person.phones.create!(number: number)
end
end
Then I ran rails generate controller contacts
and filled *models/contacts_controller.rb* with
class ContactsController < ApplicationController
def new
@contact = Contact.new
end
def create
@contact = Contact.new(contact_params)
@contact.save
redirect_to people_path
end
def contact_params
params.require(:contact).permit(:name, :number)
end
end
The next step was the view. I created views/contacts/new.html.erb and wrote this basic form
<%= form_for @contact do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :number %>
<%= f.text_field :number %>
<%= f.submit %>
<% end %>
Of course I also needed to add the route resources :contacts
That's it. Maybe it could be done more elegant. Maybe it would also pay to use only the Contacts-class, also for the other CRUD-actions. I didn't try that yet...
You can find all changes here: https://github.com/speendo/PhoneBook/tree/virtus/app/models