2014-02-14 46 views
1

我想根據兩個模型創建一個雙入口表格。導軌雙入口表

現在我能夠創建一個簡單的表與社區 normal table

在列的成員,我必須添加其他模型的信息,像這樣: double entry table

我的模型:

社區

has_many :memberships 

會員

belongs_to :user 
belongs_to :community 

用戶

has_many ::memberships 
has_many :skills 

技能

belongs_to :user 
belongs_to :community 

我有一些寶石現有做出雙列表或者是更容易使它從頭開始?如果是這樣,我該如何開始?

回答

1

正如周杰倫所說,你會受益於has_many :through的關係,或者可能是has_and_belongs_to_many relationship;無論是實際的解決方案,我們必須看到:

#app/models/user.rb 
Class user < ActiveRecord::Base 
    has_many :memberships 
    has_many :skill_users 
    has_many :skills, through: :skill_users 
end 

#app/models/skill_user.rb 
Class SkillUser < ActiveRecord::Base 
    belongs_to :skill 
    belongs_to :user 
end 

#app/models/skill.rb 
Class Skill < ActiveRecord::Base 
    has_many :skill_users 
    has_many :users, through: :skill_users 
end 

這將讓你聯想到每個user(注意:members比用戶不同),而在你的表採用雙項具有特定技能的


Relational

你正在尋找可以在關係數據庫中找到什麼樣的基礎

這些工作通過將數據存儲在單個實例中,並通過foreign_keys鏈接到其他數據。這些外鍵的東西,如user_id等:

enter image description here

more information here

這意味着,而不是填充相同的數據的兩倍,這是正確的reference,由於需要從其他模型的數據。這是join models進來


加入型號

連接模型讓您 「鏈接」 兩個數據塊通過加盟模式:

enter image description here

對你來說,這意味着將自己的技能存儲在自己的模型中,並將用戶與join model(我稱爲skill_user.rb)的技能關聯起來。這意味着你可以打電話給你的用戶這樣的技能:

@user.skills #-> goes through the join model 
3

看起來你會從這裏通過關係中受益。

而是直接從技能表引用社區,你可以這樣做:

技能

belongs_to :user 
has_many :communities, :through => :user 

在用戶,添加:

has_many :communities, :through => :memberships 

這是不是拿到之間的聯繫技能和社區,你想?