Upraszczając maksymalnie, mam dwa modele:
[code]class User < ActiveRecord::Base
has_one :profile
validates_associated :profile
validates_presence_of :nick, :password
…
end
class Profile < ActiveRecord::Base
belongs_to :user
validates_presence_of :email
…
end[/code]
Istotne akcje w kontrolerze:
[code]
def new
@user = User.new
@user.build_profile
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @user }
end
end
def create
@user = User.new(params[:user])
@user.build_profile(params[:profile])
respond_to do |format|
if @user.save
format.html { redirect_to :action => :index }
format.xml { render :xml => @user, :status => :created, :location => @user }
else
format.html { render :action => "new" }
format.xml { render :xml => @user.errors, :status => :unprocessable_entity }
end
end
end[/code]
Na koniec widok - tworzenie usera:
[code]<%= error_messages_for :user, :object => [@user, @user.profile] %>
<% form_for(@user) do |f| %>
<%= f.label :nick %> <%= f.text_field :nick %>
<%= f.label :password %> <%= f.password_field :password %>
<% fields_for @user.profile do |profile| %>
<%= profile.label :email, "E-mail" %> <%= profile.text_field :email %>
<% end %><%= f.submit "Create" , :class => "submit" %>
<% end %>[/code] Teraz do sedna sprawy... W przypadku, gdy formularze nie przechodzi walidacji, wyświetlane są komunikaty: [code] * Password can't be blank * Nick can't be blank * Profile is invalid * Email can't be blank[/code] W jaki sposób mam się pozbyć komunikatu "Profile is invalid"? Taki komunikat nic nie mówi użytkownikowi, w zupełności wystarczy mu informacja, że "Email can't be blank". Jeszcze gorzej jest, kiedy dodam do asocjacji :autosave => true, bo wtedy dostaje jeszcze komunikat "Profile email can't be blank", czyli już zupełna nadmiarowość i bezsens. Da się to jakoś sprytnie zrobić czy pozostaje ręczne stworzenie obiektu Errors z takimi komunikatami, jakie chce?