2012-10-27 51 views
1

我正在ROR中構建多客戶系統。 (我正在查看http://guides.rubyonrails.org/association_basics.html#polymorphic-associations數據庫結構 - 多用戶系統中的關聯

結構是客戶端有合同,所以當他用他的用戶名,密碼和合同登錄時,他將有權訪問系統。

我們將合同標識作爲「主密鑰」,必須位於系統的每個表中。

class CreateContracts < ActiveRecord::Migration 
    def change 
    create_table :contracts do |t| 
     t.integer :contract_id 
    end 
    end 
end 

(會計科目表)

class CreateCoas < ActiveRecord::Migration 
    def change 
    create_table :coas do |t| 
     t.integer :account_id 
     t.string :account_name 
    end 
    end 
end 


class CreateCustGroups < ActiveRecord::Migration 
    def change 
    create_table :custgroups do |t| 
     t.integer :account_id1 
     t.integer :account_id2 
     t.integer :account_id3 
    end 
    end 
end 

Q1:如何定義與belongs_to的合同?系統中的每個表格都必須與合同表有關係。我是否必須與所有表格有關係? (我認爲是)

class Contracts < ActiveRecord::Base 
    has_and_belongs_to_many :Coas 
    has_many:xxx 
    belongs:to 
end 

問題2:如何定義custgroup上的關聯?在這裏我們有一個記錄,其中有3個或更多鏈接到同一個表(COA)的字段。

+1

如果你更詳細地解釋了不同模型之間的關係,這將會有所幫助。現在,很難理解你想要達到的目標。 – Jesper

+0

喜加斯帕訂做下面 – mickdane

回答

1

正如加斯帕說,這是相當難追你想實現什麼,但我會盡力回答您的問題:

Q1:如果你希望所有的表格來引用一個合同,你「會需要添加到所有這些表一個foreign_key如contract_id 所以每個CREATE_TABLE調用將有contract_id關鍵

create_table :new_models do |t| 
    t.belongs_to :contract # this will create a contract_id field 
end 

,你還可以在列中添加索引

add_index :new_models, :contract_id 

然後在你的模型,你將添加belongs_to協會:

class NewModel 
    ... 
    belongs_to :contract 
    ... 
end 

因此,如果您Coas & CustGroups需要引用合同表,你必須同時改變遷移到包括contract_id鍵,然後模型添加belongs_to協會

如果contract需要訪問所有Coas引用它,那麼你需要使用has_many協會

class Contracts < ActiveRecord::Base 
    ... 
    has_many :coas 
    ... 
end 

這看起來不像你需要一個has_and_belongs_to_many在這裏,但我可能是錯誤的。 如果合同還需要訪問CustGroups,則需要在Contract模型中添加:

has_many :cust_groups。 Q2:我真的不明白你想做什麼。請解釋Coas和Custgroup之間有什麼關係,我會盡力幫你

+0

嗨pjam打字錯誤 - 見 對不起,我做了一個打字錯誤 應該有被 類custgroups <的ActiveRecord :: Base的不 類合約<的ActiveRecord :: Base的 我有一個客戶我必須鏈接到我的帳戶中的不同帳戶 我需要我的客戶組中的每個記錄有3個帳戶 – mickdane

+0

但我看到我可以做我想要的 - 很多thanx – mickdane

+0

嗯,我沒有真正得到什麼你說過,我的答案也幫助過你,還是需要更多的解釋? – pjam