最后得到这个工作使用嵌套属性。正如肯顿答案的评论中所讨论的那样,这个例子是相反的。如果您想为每个帐户创建多个用户,则必须先创建帐户,然后再创建用户 - 即使您只创建一个用户开始。然后你编写自己的账户控制器和视图,绕过设计视图。发送确认电子邮件等的设计功能似乎仍然工作,如果你只是直接创建一个用户,即该功能必须是在Devise 模型中的自动化东西的一部分;它不需要使用Devise控制器。
摘录相关文件:
模式在app /型号
class Account < ActiveRecord::Base
has_many :users, :inverse_of => :account, :dependent => :destroy
accepts_nested_attributes_for :users
attr_accessible :name, :users_attributes
end
class User < ActiveRecord::Base
belongs_to :account, :inverse_of => :users
validates :account, :presence => true
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable,
:confirmable, :lockable, :timeoutable
attr_accessible :email, :password, :password_confirmation, :remember_me
end
规格/型号/ account_spec.rb RSpec的模型试验
it "should create account AND user through accepts_nested_attributes_for" do
@AccountWithUser = { :name => "Test Account with User",
:users_attributes => [ { :email => "[email protected]",
:password => "testpass",
:password_confirmation => "testpass" } ] }
au = Account.create!(@AccountWithUser)
au.id.should_not be_nil
au.users[0].id.should_not be_nil
au.users[0].account.should == au
au.users[0].account_id.should == au.id
end
配置/ routes.rb
个
resources :accounts, :only => [:index, :new, :create, :destroy]
控制器/ accounts_controller.rb
class AccountsController < ApplicationController
def new
@account = Account.new
@account.users.build # build a blank user or the child form won't display
end
def create
@account = Account.new(params[:account])
if @account.save
flash[:success] = "Account created"
redirect_to accounts_path
else
render 'new'
end
end
end
视图/帐户/ new.html.erb视图
<h2>Create Account</h2>
<%= form_for(@account) do |f| %>
<%= render 'shared/error_messages', :object => f.object %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<%= f.fields_for :users do |user_form| %>
<div class="field"><%= user_form.label :email %><br />
<%= user_form.email_field :email %></div>
<div class="field"><%= user_form.label :password %><br />
<%= user_form.password_field :password %></div>
<div class="field"><%= user_form.label :password_confirmation %><br />
<%= user_form.password_field :password_confirmation %></div>
<% end %>
<div class="actions">
<%= f.submit "Create account" %>
</div>
<% end %>
Rails是相当挑剔复数与单数。既然我们说的帐号的has_many用户:
- ,预计在模型users_attributes(不user_attributes)和测试
- 预计的阵列的哈希值进行测试,即使数组中只有一个元素是,因此{{用户属性}周围的[]。
- 它期望在控制器中使用@ account.users.build。我无法使f.object.build_users语法直接在视图中工作。
是“new.html.erb”设计视图(例如app/views/devise/registrations/new.html.erb)? – y0mbo
@ y0mbo,no,new.html.erb在views/accounts下。我已经添加了解决问题的途径。另见关于“绕过Devise视图”的第一段以及它的工作原理。基本上我使用帐户#创建操作来创建帐户和用户,所以我不需要Devise视图。 –
谢谢!这是一个很好的答案和明确的解决方案。 – y0mbo