In my Rails 3 App, my fields for won't associate, I've been researching and I can't figure out why.
My view:
= form_for(resource, class: 'admin_form', :as => resource_name, :url => registration_path(resource_name)) do |f|
= devise_error_messages!
.admin_form
...
= fields_for :profile do |p|
...
%dl
%dd
= f.submit "Sign up", class: "btn"
Controller:
class RegistrationsController < Devise::RegistrationsController
before_filter :check_admin_quantity
def new
super
@profile = @user.build_profile
end
Model:
class User < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation, :remember_me, :current_password, :profile_attributes
has_one :profile, dependent: :destroy
accepts_nested_attributes_for :profile
Firstly use f.fields_for
instead of fields_for
. The later only creates the fields, but they are not associated with a form object, former is creating fields for associated object.
When you add f.
you will notice that it is not rendering fields. It is caused by your resource
not having associated profile. You are building profile on @user
, but it is different than resource
object.
If you have a look at default implementation of new, it reads:
def new
build_resource({})
respond_with self.resource
end
you are calling this calling super in your new method. You need to build profile between build_resource
and respond_with
, so your new
action should be:
def new
build_resource({})
resource.build_profile
respond_with self.resource
end