验证失败后保留嵌套的表单字段值

时间:2013-06-14 17:47:15

标签: ruby-on-rails ruby ruby-on-rails-3

我是rails的新手,还没有设法解决以下问题。我使用devise进行身份验证,使用名为“user”的模型。该模型与另一个名为“公司”的模型相关联:

user.rb

  class User < ActiveRecord::Base

  devise :database_authenticatable, :registerable, :confirmable,
         :recoverable, :rememberable, :trackable, :validatable

  belongs_to :company
  accepts_nested_attributes_for :company

  attr_accessible :company_attributes, :email, :password, 
                  :password_confirmation, :remember_me, :company_id

company.rb

  class Company < ActiveRecord::Base

  has_many :users
  attr_accessible :name
  validates :name, :presence => true, :uniqueness => true

注册时,用户同时创建公司和用户:

users_controller.rb

def new
    @user = User.new
    @user.build_company

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @user }
    end
end

def create
  @user = User.new(params[:user])

  respond_to do |format|
    if @user.save
      format.html { redirect_to @user, notice: 'User was successfully created.' }
      format.json { render json: @user, status: :created, location: @user 
    else
      format.html { render action: 'new' }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end

到目前为止,注册工作正常,这意味着如果@user.save为真,则在用户和公司模型中分别创建两条记录,并在用户模型的列company_id中创建正确的关联。

如果@user.save为false,例如因为已经拍摄了用户属性电子邮件的验证失败,则会呈现新视图。正如所料,@user属性(在本例中为电子邮件)将保留,并保留在render action: 'new'之后的相应表单字段中。但是,公司属性名称的表单字段显示为空白。这是注册页面的视图:

new.html.erb

<%= devise_error_messages! %>
<h2>Sign up</h2>
<%= simple_form_for(resource, :as => resource_name, 
                              :url => registration_path(resource_name),
                              :html => {:class => 'form-horizontal' }) do |f| %>

    <%= f.simple_fields_for :company,  @user.build_company do |builder| %>
        <div><%= builder.label :name, "Company" %><br />
        <%= builder.text_field :name, :autofocus => true, 
                            :placeholder => "Example Company Inc.",
                            :required => true %></div>
    <% end %>

  <div><%= f.label :email %><br />
  <%= f.email_field :email, :placeholder => "example@email.com",  :required => true %></div>

  <div><%= f.label :password %><br />
  <%= f.password_field :password,  :required => true %></div>

  <div><%= f.label :password_confirmation %><br />
  <%= f.password_field :password_confirmation,  :required => true %></div>

  <%= f.submit "Sign up", :class => "btn"%>
<% end %>

<%= render "devise/shared/links" %>

我认为我可能必须在用户创建方法中创建一个实例变量@company,以便表单字段内容可以保存在params哈希中,如下所示:

@company = @user.build_company(params[:company])

不幸的是,这不起作用,到目前为止,我还没有在stackoverflow上发布的其他问题中找到解决方案。我期待您的意见,以便我可以继续构建我的第一个应用程序;)

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

感谢Michal的输入,我重新安排了我的控制器,以便通过关联公司创建用户,而不是相反。各自的公司控制器如下所示:

<强> companies_controller.rb

# GET company/new
def new
    @company = Company.new
    @company.users.build
end

# POST company/
def create
    @company = Company.new(params[:company])

    respond_to do |format|
      if @company.save
        format.html { redirect_to root_path, notice: 'Welcome! Your account has been created successfully. A confirmation link has been sent to your email address.' }
        format.json { render json:  root_path, status: :created, location: @company }
      else
        format.html { render action: "new" }
        format.json { render json: @company.errors, status: :unprocessable_entity }
      end
    end
end

GET请求的格式嵌套在Devise用户模型字段中,如下所示:

<强> new.html.erb

<h2>Create an account</h2>
<%= simple_form_for( @company, :html => {:class => 'form-horizontal' }) do |f| %>
<%= render 'shared/error_messages', :object => @company %>
    <%= f.input     :name, 
                    :label =>'Company name',
                    :placeholder => "Example Company Inc.",
                    :autofocus => true %>
    <%= f.simple_fields_for :users do |builder| %>
        <%= builder.input   :email, 
                            :placeholder => "example@email.com" %>
        <%= builder.input :password %>
        <%= builder.input :password_confirmation %>
    <% end %>
    <%= f.button    :submit, 'Create account',
                    :class => 'btn'%>
<% end %>
<%= link_to "Sign in", new_session_path(:user) %>

现在,如果验证失败,则所有实例属性值都保留在各自的表单字段中。