0

我正在使用设计对用户进行身份验证,当新用户注册时,我也想创建新帐户,并将此用户设置为帐户的所有者。我决定为此使用带有嵌套模型的表单。这是我的设置:

楷模:

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 路径时不会引发异常,但不会生成表单的嵌套部分。已经有几个类似的问题,但提供的解决方案似乎对我不起作用......

4

2 回答 2

0

根据您的代码:

def new
  super
  owned_account = resource.build_owned_account 
end

在您的视图中无法访问变量owned_account。如何将该行替换为:

resource.owned_account = resource.build_owned_account
于 2013-04-23T12:36:37.827 回答
0

问题在于super在覆盖控制器中使用。此代码有效:

class RegistrationsController < Devise::RegistrationsController
   def new
      resource = build_resource({})
      resource.build_owned_account
      respond_with resource
   end

   def create
     super
   end
end
于 2013-04-23T12:54:33.233 回答