Ответ 1
Наконец, это получило работу с использованием вложенных атрибутов. Как обсуждалось в комментариях к Kenton, этот пример отменяется. Если вам нужно несколько пользователей на одну учетную запись, сначала необходимо создать учетную запись, а затем Пользователь - даже если вы только создаете одного пользователя для начала. Затем вы пишете свой собственный контроллер учетных записей и просматриваете, минуя представление "Разработать". Функциональность Devise для отправки писем с подтверждением и т.д. По-прежнему работает, если вы просто создаете пользователя напрямую, т.е. Эта функциональность должна быть частью автомата в модели Devise; он не требует использования контроллера Devise.
Выдержки из соответствующих файлов:
Модели в приложении/моделях
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 => "[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
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 %>
Рельсы довольно разборчивы по поводу множественного числа и единственного числа. Поскольку мы говорим, что Account has_many Users:
- он ожидает, что user_attributes (а не user_attributes) в модели и тестах
- он ожидает массив хэшей для теста, даже если в массиве есть только один элемент, поэтому [] вокруг {user attributes}.
- он ожидает @account.users.build в контроллере. Мне не удалось заставить синтаксис f.object.build_users работать непосредственно в представлении.