2012-11-29 33 views
2

我正在嘗試實現可以​​擁有一個或多個用戶的頂級帳戶。我的應用程序使用Devise進行身份驗證,因此我希望將註冊表單保留爲用戶模型的一部分。添加一個擁有許多「用戶」的「帳戶」

我相信我已經正確設置了模型,但我在確定註冊表的工作方式時遇到了一些麻煩。

這裏就是我這麼遠......

User.rb

class User < ActiveRecord::Base 
    rolify 
    # Include default devise modules. Others available are: 
    # :token_authenticatable, :confirmable, 
    # :lockable, :timeoutable and :omniauthable 
    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, 
     :validatable, :omniauthable 

    # Setup accessible (or protected) attributes for your model 
    attr_accessible :role_ids, :as => :admin 
    attr_accessible :name, :email, :password, :password_confirmation, :remember_me, :account, :company 

    # Association with service accounts 
    has_many :service_accounts 

    # Association with company account 
    belongs_to :account 

end 

Account.rb

class Account < ActiveRecord::Base 
    attr_accessible :company 

    # Association with users 
    has_many :users, :dependent => :destroy 

end 

註冊/ new.html。 erb

<h2>Sign up</h2> 
<%= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => {:class => 'form-vertical' }) do |f| %> 
    <%= f.error_notification %> 
    <%= f.input :name, :autofocus => true, :placeholder => "Name" %> 
    <%= f.input :email, :placeholder => "Email Address" %> 
    <%= f.input :password, :placeholder => "Password" %> 
    <%= f.input :password_confirmation, :placeholder => "Confirm Password" %> 
    <%= f.button :submit, 'Sign up', :class => 'btn btn-large btn-primary' %> 
<% end %> 
<%= render "devise/shared/links" %> 

以下是我可以利用一些幫助與

我想一個「公司」字段添加到上面的登記表。公司是賬戶表中的一列。當新用戶註冊時,我想爲該用戶創建一個新帳戶,並將公司屬性設置爲他們在公司字段中提供的任何內容。

我在爲表單(添加公司字段)和控制器(創建新帳戶並在用戶提交表單時更新公司字段)所需的代碼遇到問題。

謝謝!

回答

1

我剛剛完成了一個具有類似要求的應用程序。這段關係看起來不錯。您很可能需要User上的before_save篩選器,該篩選器將數據與Account關聯,並同時添加/更新關聯。

你也應該看看accepts_nested_attributes_for,雖然我認爲它的目的是處理父母(帳戶,在你的情況)驅動兒童(用戶)的創作的更常見的情況。我懷疑你正在用Devise創建一個用戶,然後創建關聯,並將相關數據添加到帳戶模型。

需要思考的是公司是否是自己的模型,在這種情況下,用戶擁有賬戶,賬戶擁有公司。您可能需要查看最近的RailsCasts on "multi-tenant" applications - 雖然它們可能不適用於您的案例,但它們是我的,並且在我第一次啓動應用程序時管理和構建數據時,有幾件事我沒有想過。

+0

感謝您的提示。我認爲'before_save'是要走的路。現在查看'accept_nested_attributes_for'。可以使用一些代碼示例! – Eric

+0

代碼示例在這裏:https://github.com/tomharrisonjr/recipe-box(這是我在多對多的情況下試圖找出accept_nested_attributes_for')。 :-) –

相關問題