I am developing an application in Rails, which i use Devise for user authentication. But I need more than one type of user, each user type has different types of data, leaving devise for only authentication. I already had created a post about this, with better explanations of the situation, here , but i could not solve the problem , so sorry for creating another post.
My codes:
user.rb
class User < ActiveRecord::Base
belongs_to :profileable, :polymorphic => true
accepts_nested_attributes_for :profileable, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
patient.rb
class Patient < ActiveRecord::Base
has_one :user, :as => :profileable
accepts_nested_attributes_for :user, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
end
patients_controller.rb
def new
@patient = Patient.new
@user = @patient.build_user
end
def create
@patient = Patient.new(patient_params)
@user = @patient.build_user(params[:user])
@user.profileable = @patient
if @user.save
@patient.save
redirect_to @patient
else
render 'new'
end
end
private
def patient_params
params.require(:patient).permit(:name, user_attributes:[:email, :password, :password_confirmation])
end
_form.html.erb
<%= form_for @patient, :url => patients_path(@patient), :html => {:method => :post} do |f| %>
<%= f.label :name, "Nome" %><br>
<%= f.text_field :name, placeholder:"Digite o nome do Paciente", required:"", autofocus: true %>
<br>
<%= f.fields_for :user do |u| %>
<%= u.label :email %><br />
<%= u.email_field :email %><br/>
<%= u.label :password %><br/>
<%= u.password_field :password, autocomplete: "off" %><br/>
<%= u.label :password_confirmation %><br />
<%= u.password_field :password_confirmation, autocomplete: "off" %><br/>
<% end %>
<%= f.submit "Ok" %>
<% end %>
user migration
t.integer :profileable_id
t.string :profileable_type
And devise attrs
The idea is creating an user and a patient (or other type of user) at the same time, on the form_for patients. And the error i'm getting is:
The user dont save! When i submit the form, the user dont save and i get a "rollback".
Can someone please help me?
Aucun commentaire:
Enregistrer un commentaire