终于使用嵌套属性让它工作了。正如在肯顿回答的 cmets 中所讨论的那样,这个例子是相反的。如果您希望每个帐户有多个用户,则必须先创建帐户,然后再创建用户——即使您一开始只创建一个用户。然后你编写自己的 Accounts 控制器和视图,绕过 Devise 视图。如果您只是直接创建用户,则用于发送确认电子邮件等的设计功能似乎仍然有效,即该功能必须是 Devise model 中自动功能的一部分;它不需要使用设计控制器。
相关文件的摘录:
模型在应用/模型中
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
spec/models/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 => "user@example.com",
: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
config/routes.rb
resources :accounts, :only => [:index, :new, :create, :destroy]
controllers/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
views/accounts/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)
- 它需要一个 数组 哈希用于测试,即使数组中只有一个元素,因此 {user attributes} 周围有 []。
- 它需要控制器中的@account.users.build。我无法让 f.object.build_users 语法直接在视图中工作。