This is for Rails 4.04 and Ruby 2.1. I'd like to allow my users to have addresses. So I generated an address table and gave it columns (NUMBER, STREET, CITY, STATE). Now when I go to the following url, I'd like to be able edit this information:
webapp.com/users/edit/
However I noticed it only showed the same old information (name, password, email). So I went to the view and added simple_fields for my new relationship so the view now looks like this:
<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
<div class="form-inputs">
<%= f.input :email, required: true, autofocus: true %>
<%= f.input :name, required: false %>
<%= f.simple_fields_for :addresses do |a| %>
<%= a.input :number %>
<%= a.input :street %>
<%= a.input :city %>
<%= a.input :state %>
<%= a.input :country %>
<% end %>
<%end%>
However it still doesn't generate the fields needed for address. I think this is because none of my users currently have any addresses attached to their account profile (because this migration was just created). However, in this case there should be blank fields generated so I can ADD address information.
I feel like I need to do something in the Users#Edit action like this
@users.each do |user|
user.address.build
end
Is that right? How can I override the users controller because this was created by Devise and I don't actually have a users controller (I looked for it it and couldn't find it).
UPDATE
Ok, I'm getting closer. I had to create my own controller to override Devise's default registrations controller as explained in the second answer of this stack overflow article:
Override devise registrations controller
So now I am getting into that controller which currently looks like this:
class Users::RegistrationsController < Devise::RegistrationsController
def edit
super
end
end
However, when I get to my view, it's still SKIPPING the block that starts like this:
<%= f.simple_fields_for :addresses do |a| %>
However, if I go manually into my DB and add a record in the addresses table and link it to my currently_signed in user via the foreign key, then the block does not get skipped. So whats the best way to generate this connection if the address record does not yet exist? Is it the build method? e.g.
user.address.build
in the controller
SOLUTION
Yes, I needed to added this method to my new registrations_controller.rb file
def edit
if resource.addresses.size == 0
resource.addresses.build
end
super
end
It is now working the way I intended it.