I develop RoR app and i met thing which i can’t solve. I have 2 models – User and Teacher.
class User < ActiveRecord::Base
...
has_one :teacher
accepts_nested_attributes_for :teacher
end
class Teacher < ActiveRecord::Base
...
belongs_to :user
end
Also i have view with forms for fill data of User and Teacher. After submit data from this form goes in other method of my controller – create_teacher. Also i have other method new_teacher, in this method i have my view with forms.
class AdminsController < ApplicationController
def new_teacher
@user = User.new
teacher = @user.build_teacher
end
def create_teacher
params[:user][:user_role] = "teacher"
user = User.new(params[:user])
if user.valid?
user.save
teacher = user.build_teacher( params[:user][:teacher_attributes] )
if teacher.valid?
teacher.save
redirect_to admins_users_of_system_path
flash[:success] = "Teacher created!"
else
redirect_to admins_new_teacher_path
flash[:error] = teacher.errors.full_messages.to_sentence
user.destroy
end
else
redirect_to admins_new_teacher_path
flash[:error] = user.errors.full_messages.to_sentence
end
end
end
My view new_teacher.html.erb
<%= form_for @user, :url => create_teacher_url, :html => {:class => "form-horizontal"} do |f| %>
<%= field_set_tag do %>
<%= f.fields_for :teacher do |builder| %>
<div class="control-group">
<%= builder.label :teacher_last_name, "Last name", :class => "control-label" %>
<div class="controls">
<%= builder.text_field :teacher_last_name %>
</div>
</div>
...
<% end %>
<div class="control-group">
<%= f.label :user_login, "Login", :class => "control-label" %>
<div class="controls">
<%= f.text_field :user_login, :value => "" %>
<%= link_to_function "Generate login", "generate_login()", :class => "btn" %>
</div>
</div>
...
<% end %>
<%= f.submit "Create", :class => "btn btn-large btn-success" %>
<% end %>
I have 2 questions:
1) How can i show all errors (for user and teacher)? Is that possible?
2) Is that possible to keep my data in forms when i redirect to admins_new_teacher_path from create_teacher method?
I found right solution. For this we should use accepts_nested_attributes_for. Then, when we did this when we create to models
Here we get all errors by
user.errors.