Rails + Devise自定义视图不会显示错误后填充好的嵌套字段

时间:2014-12-30 16:34:16

标签: ruby-on-rails devise

Hy使用rails-3.2.13devise-3.4.1。 我已经覆盖了这些观点:

rails g devise:views 

我已定制new.html.erb视图:

  <%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
      <%= devise_error_messages! %>

        <%= f.fields_for :profile,resource.build_profile do |organization_form| %>
                <%= organization_form.text_field :name %>
                <%= organization_form.text_field :surname %>
        <% end %>

        <%= f.email_field :email %>
        <%= f.password_field :password %>
        <%= f.password_field :password_confirmation %>
        <%= f.submit "Sign Up" %>

  <% end %>

除非存在验证错误,否则一切正常。表单organization_form未填写用户输入,而表单f填写完整。因此:验证错误后,:name:surname不会重新填充。

这是我的用户模型:

class User < ActiveRecord::Base
  ...  
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_one :profile, :dependent => :destroy

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me
  attr_accessible :profile_attributes
  accepts_nested_attributes_for :profile
  ....
end

你能帮助我吗?

1 个答案:

答案 0 :(得分:0)

它应该是<% resource.profile || resource.build_profile %>,否则您将无法在表单失败时填写传递的值。 所以new.html.erb现在是这样的:

<% resource.profile || resource.build_profile %>
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
      <%= devise_error_messages! %>

        <%= f.fields_for :profile do |organization_form| %>
                <%= organization_form.text_field :name %>
                <%= organization_form.text_field :surname %>
        <% end %>

        <%= f.email_field :email %>
        <%= f.password_field :password %>
        <%= f.password_field :password_confirmation %>
        <%= f.submit "Sign Up" %>

<% end %>