我正在使用设计对用户进行身份验证,当新用户注册时,我也想创建新帐户,并将此用户设置为帐户的所有者。我决定为此使用带有嵌套模型的表单。这是我的设置:
楷模:
class User < ActiveRecord::Base
belongs_to :account
has_one :owned_account, :class=> Account, :foreign_key => :owner_id
accepts_nested_attributes_for :owned_account
end
class Account < ActiveRecord::Base
has_many :users
belongs_to :owner, :class => User, :foreign_key => :owner_id
end
路线:
devise_for :users, :path_prefix => 'authentication', :controllers => {:registrations => "registrations"}
resources :accounts
重写设计注册控制器:
class RegistrationsController < Devise::RegistrationsController
def new
super
owned_account = resource.build_owned_account
end
def create
super
end
end
形式:
<%= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :email, :required => true, :autofocus => true %>
<%= f.input :password, :required => true %>
<%= f.input :password_confirmation, :required => true %>
<%= f.simple_fields_for :owned_account do |account| %>
<%= account.input :name, :required => true %>
<% end %>
</div>
<div class="form-actions">
<%= f.button :submit, "Sign up" %>
</div>
<% end %>
访问 sign_up 路径时不会引发异常,但不会生成表单的嵌套部分。已经有几个类似的问题,但提供的解决方案似乎对我不起作用......