Rails3中+设计+ simple_form + nested_model

时间:2013-04-23 12:15:22

标签: ruby-on-rails model devise nested simple-form

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

模型:

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

2 个答案:

答案 0 :(得分:0)

根据你的代码:

def new
  super
  owned_account = resource.build_owned_account 
end

您的视图中无法访问变量owned_account。如何用以下代码替换该行:

resource.owned_account = resource.build_owned_account

答案 1 :(得分:0)

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

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

   def create
     super
   end
end