【发布时间】:2018-04-15 00:08:05
【问题描述】:
我已将 Devise 设置为创建 Accounts,这些帐户与 Businesses 和 Personnel 相关联。当您注册新帐户时,我正在尝试找到一种包含人员信息和业务信息的方法。有没有办法扩展新的注册表单?我还希望它根据哪个单选按钮处于活动状态(默认为人员)而改变。我认为嵌套形式是要走的路,但老实说,我不知道如何去做。
商业模式和人事模式都有这条线……
app/models/Business.rb & app/models/Personnel.rb
has_one :account, as :accountable
Account 模型看起来像这样......
app/models/Account.rb
class Account < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
belongs_to :accountable, polymorphic: true
ACCOUNT_TYPES=["SuperAccount","Chamber","Personnel", "Business"]
attr_accessor :type
end
以下是我设置注册控制器的方法,以防万一。
app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
def new
super
end
def create
build_resource(sign_up_params)
if (resource.type=="Personnel")
resource.accountable = Personnel.new
SignupNotifierMailer.personnel(@account).deliver
elsif(resource.type =="Business")
resource.accountable = Business.new
SignupNotifierMailer.business(@account).deliver
end
resource.save
yield resource if block_given?
if resource.persisted?
if resource.active_for_authentication?
set_flash_message! :notice, :signed_up
sign_up(resource_name, resource)
respond_with resource, location: after_sign_up_path_for(resource)
else
set_flash_message! :notice, :"signed_up_but_#{resource.inactive_message}"
expire_data_after_sign_in!
respond_with resource, location: after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords resource
set_minimum_password_length
respond_with resource
end
end
def destroy
@account.accountable.destroy!
super
end
protected
def after_sign_up_path_for(resource)
if (resource.type == 'Personnel')
edit_personnel_path(current_account.accountable_id)
elsif (resource.type == 'Business')
edit_business_path(current_account.accountable_id)
else
super
end
end
end
最后,这是我想要改变的观点。
app/views/devise/registrations/new.html.erb
<h2>Sign Up</h2>
<%= simple_nested_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, hint: ("#{@minimum_password_length}
characters minimum" if @minimum_password_length) %>
<%= f.input :password_confirmation, required: true %>
<%= f.input :type, required: true, as: :radio_buttons, label: "Type of Account",
collection: Account::ACCOUNT_TYPES.drop(2), checked: 'Personnel' %>
</div>
<div class="form-actions">
<%= f.button :submit, "Sign Up" %>
</div>
<% end %>
【问题讨论】:
标签: ruby-on-rails ruby devise nested-forms