2010-05-05 119 views
0

我不知道我在做這些正確的。如何將新條目添加到多個has_many關聯?

我有3個模型,帳戶,用戶和事件。

帳戶包含一組用戶。每個用戶都有自己的用戶名和密碼用於登錄,但他們可以在同一帳戶下訪問相同的帳戶數據。

事件是由用戶創建的,同一帳戶中的其他用戶也可以讀取或編輯它。

我創建了以下遷移和模型。


用戶遷移

class CreateUsers < ActiveRecord::Migration 
    def self.up 
    create_table :users do |t| 
     t.integer  :account_id 
     t.string  :username 
     t.string  :password 
     t.timestamps 
    end 
    end 

    def self.down 
    drop_table :users 
    end 
end 

帳戶遷移

class CreateAccounts < ActiveRecord::Migration 
    def self.up 
    create_table :accounts do |t| 
     t.string  :name 
     t.timestamps 
    end 
    end 

    def self.down 
    drop_table :accounts 
    end 
end 

事件遷移

class CreateEvents < ActiveRecord::Migration 
    def self.up 
    create_table :events do |t| 
     t.integer  :account_id 
     t.integer  :user_id 
     t.string  :name 
     t.string  :location 
     t.timestamps 
    end 
    end 

    def self.down 
    drop_table :events 
    end 
end 

帳戶模式

class Account < ActiveRecord::Base 
    has_many  :users 
    has_many  :events 
end 

用戶模式

class User < ActiveRecord::Base 
    belongs_to :account 
end 

事件模型

class Event < ActiveRecord::Base 
    belongs_to :account 
    belongs_to :user 
end 

左右....

  1. 這是設置是否正確?
  2. 每次用戶創建一個新帳戶時,系統都會詢問用戶信息,例如,用戶名和密碼。我如何將它們添加到正確的表格中?
  3. 如何添加新事件?

對於這麼長的問題,我感到抱歉。我並不十分理解處理這種數據結構的方式。謝謝你們回答我。:)

+0

您確定要自動創建用戶名和密碼嗎?這不是通過表單向用戶提供的嗎? – Tarscher 2010-05-05 08:03:32

+0

用戶在帳號註冊過程中需要輸入自己的用戶名和密碼。感謝好友 – 2010-05-05 08:12:58

回答

2

這看起來像has_many :through工作(向下滾動找到:through選項)

如果您需要知道創建事件的用戶,那麼你應該只指定事件真正屬於用戶:

class Event < ActiveRecord::Base 
    belongs_to :user 
end 

然而,帳戶可以「抓取」他們用戶的事件。您指定這樣的:

class User < ActiveRecord::Base 
    belongs_to :account 
end 

class Account < ActiveRecord::Base 
    has_many :users 
    has_many :events, :through => :users 
end 

的遷移將是一樣的,你寫了AccountUser。對於Event您可以刪除account_id

class CreateEvents < ActiveRecord::Migration 
    def self.up 
    create_table :events do |t| 
     t.integer  :user_id 
     t.string  :name 
     t.string  :location 
     t.timestamps 
    end 
    end 

    def self.down 
    drop_table :events 
    end 
end 

然後您的活動可以這樣創建:

# These two are equivalent: 
event = user.events.create(:name => 'foo', :location => 'bar') 
event = Event.create(:user_id => user.id, :name => 'foo', :location => 'bar') 

注意,這將創建並保存inmediately事件。如果您想在不保存的情況下創建事件,則可以使用user.events.buildEvent.new代替。

上的帳戶的has_many :through將讓你得到所有事件的一個帳戶:

user.events   # returns the events created by one user 
account.events  # returns all the events created by the users of one account 
user.account.events # returns the events for the user's account 

最後一點,請注意,您在這裏重新發明輪子了很多。有很好的解決方案來管理用戶和權限。

我建議你有管理權限看看deviserailscast)或authlogicrailscast),用於管理您的帳戶,並declarative_authorizationrailscast)或cancanrailscast)。我個人的選擇是設計和聲明授權。前者比authlogic更容易安裝,後者比cancan更強大。

問候,祝你好運!

+0

。我長期尋找這些寶石。將深入研究設計和聲明授權。 – 2010-05-05 09:24:18

相關問題