2013-03-12 111 views
0

我正在实现拥有许多用户的顶级帐户。用帐户和用户设计身份验证

我正在关闭这个问题的解决方案: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 %> 

回答

1

您需要手动登录用户。在账户控制器,你需要一个sign_in(user),其中user是要签名的实际User模型记录英寸

问题是,你有一个帐户,许多用户的关系。因此,你需要获得进入单用户以某种方式,如:

def create 
    @account = Account.new(params[:account]) 
    if @account.save 
     sign_in(@account.users.first) 
     flash[:success] = "Account created" 
     redirect_to accounts_path 
    else 
     render 'new' 
    end 
    end 
+0

非常感谢。我粘贴了大概二十几个方法/参数组合,但似乎无法得到正确的用户。这工作完美。 – Eric 2013-03-12 20:05:21

1

您需要

before_filter :authenticate_user!, :except => [:new,:create] 

添加到账户控制器,以提供身份验证行动的其余