Topic: Writing to a second model when using Devise
Hi everyone,
I'm trying to make a simple app where users can sign up and will have a basic profile page that is unique to their account.
I'm using Devise for the authentication, and I have created a Profile model where individual user information will be stored.
I want Devise to create a new record in the Profiles table when a new user is created. I believe I need to edit the create action in the Devise controller but don't know how to access that.
I read that I should create a controller for my model (Which in this case is ProfilesController), which I did. I've got the following controller code:
class ProfilesController < Devise::RegistrationsController
def new
@user.profile = Profile.new
def create
@profile = @user.profiles.build(params[:profile])
if @project.save
redirect_to :action => 'index'
else
render :action => 'new'
end
end
endThe code in my profile.rb and user.rb is:
#profile.rb
class Profile < ActiveRecord::Base
attr_accessible :name
belongs_to :user
end
#user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable, :lockable and :timeoutable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :name, :email, :password, :password_confirmation, :remember_me
has_one :profile
endAnd my signup page for Devise is currently:
<h2>Sign up</h2>
<% resource.build_profile %>
<%= form_for(resource, :as => resource_name,
:url => registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<p><%= f.label :name %><br />
<%= f.text_field :name %></p>
<p><%= f.label :email %><br />
<%= f.text_field :email %></p>
<p><%= f.label :password %><br />
<%= f.password_field :password %></p>
<p><%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation %></p>
<%= f.fields_for :profile do |profile_form| %>
<p><%= profile_form.label :name %><br />
<%= profile_form.text_field :name %></p>
<% end %>
<p><%= f.submit "Sign up" %></p>
<% end %>
<%= render :partial => "devise/shared/links" %>(I have two name fields just so I can see that it writes it to Profile, but I would like to combine it into one field but written into two models, User and Profile).
So right now it's not working, and I think I need to get access into the Devise controller but I don't know how to do that. I want the user signup process to be linked to a new profile creation, and some of the information collected in the signup process to be written to that new profile record which is linked directly (so I can handle permissions etc later) to that particular user.
Any tips or guidance would be much appreciated.
Thanks for the help.
- Raoul