2
votes

ROR newbie here. :-)

I am using Devise for authentication and have added first_name and last_name to the User model created by devise. I have also created Address model:

create_table :addresses do |t| t.string :line1 t.string :line2 t.string :city t.string :state t.integer :addressable_id t.string :addressable_type

  t.timestamps
end

add_index :addresses, [:addressable_type, :addressable_id], :unique => true 

end


a partial at views/shared/_address.html.erb






user.rb

has_one :address, :as => :addressable

# Include default devise modules. Others available are: # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable

# Setup accessible (or protected) attributes for your model attr_accessible :email, :password, :password_confirmation, :remember_me, :firstname, :lastname attr_accessible :address_attributes

accepts_nested_attributes_for :address, :update_only => true

added the following lines at views/devise/registrations/new.html.erb and edit.html.erb


<% f.fields_for :address do |address|%> <%= render :partial => 'shared/address', :locals => {:f => address}%>

<% end %>

<% end %>


<% f.fields_for :address do |address|%> <%= render :partial => 'shared/address', :locals => {:f => address}%>

<% end %>

<% end %>


Now I want to have Devise create an Address when a new user sign up. And the user could fill in the address after sign in. Apparently something is missing or I am doing it wrong. The address fields are not showing at sign_up nor edit.

Please share your wisdom. Thanks in advance.

1

1 Answers

3
votes

The general behavior of fields_for is that the associated object will not show in the form unless it already exists. E.g. if we were speaking outside the context of Devise, then to get the address to show up on the new user form you would have something like:

# users_controller.rb
def new
   @user = User.new
   @user.address = Address.new
end

and then the address would display on the form.

Given that this is a Devise-managed form and you do not have direct access to the necessary controller, I'm guessing the best thing to do is to use an ActiveRecord callback to instantiate an address if it doesn't exist already. E.g. something like

# user.rb
after_initialize :create_address

def create_address
    self.address = Address.new if self.address.nil?
end