I have created a simple Rails app, that uses devise. For logging in and out I use the standard USER model that has email + password. I have a PROFILE model to store all the other details for the user.
I want to create a page where the user can update all their details. Currently getting the following error...
NoMethodError in UsersController#update
undefined method `name' for nil:NilClass
Screenshot of entire error message
My models look as so...
class User < ApplicationRecord
Include default devise modules. Others available are:
:confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable
has_one :profile
after_create :create_profile
attr_accessor :first_name, :last_name, :description
accepts_nested_attributes_for :profile
end
class Profile < ApplicationRecord
belongs_to :user
end
View page code looks like...
<h1>Account Details</h1>
<p><strong>Email:</strong> <%= @user.email %></p>
<p><strong>First Name:</strong> <%= @user.profile.first_name %></p>
<p><strong>Last Name:</strong> <%= @user.profile.last_name %></p>
<%= form_for(@user, :as => :user) do |field| %>
<p>
<%= field.label :email %>
<%= field.text_field :email %>
</p>
<%= fields_for @user.profile do |profile| %>
<p>
<%= profile.label :first_name %><br>
<%= profile.text_field :first_name %>
<% end %>
</p>
<p>
<%= field.submit "Update" %>
</p>
<% end %>
and the Controller looks like
Class UsersController < Devise::RegistrationsController
def new
build_resource({})
resource.build_profile
respond_with self.resource
end
def create
super
end
def edit
super
end
def update
@user = current_user
end
def show
@user = current_user
end
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up) { |u|
u.permit(:email, :password, [profile_attributes: [ :first_name, :last_name]])
}
end
end
I can't get this form to render and update the models. I hope someone can tell me what I am doing wrong.