我正在实施一个拥有许多用户的顶级帐户。
我正在解决这个问题: Use both Account and User tables with Devise
什么有效:
用户提交注册表(如下)后,将根据需要创建用户和帐户。
什么不起作用:
用户未在 redirect_to accounts_path 之前进行身份验证。为了进行身份验证,用户必须单击登录并输入他们刚刚注册的凭据。相反,我需要在重定向之前对用户进行身份验证。
我已经为此工作了几个小时,尝试了几种方法,但似乎没有任何效果。
成功创建用户/帐户后,有人可以帮助我使用代码对用户进行身份验证。谢谢!
楷模
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
路线
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
视图/帐户/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 %>