2013-03-12 114 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] 

添加到賬戶控制器,以提供身份驗證行動的其餘