2016-02-01 27 views
0

在Ruby on Rails項目中,我有一些複雜的數據庫結構。甲用戶可以有許多EmailAccounts,一個EmailAccount可以有許多訂閱訂閱可以有許多標籤(也許多-TO-(通過一個連接表許多一對多)許多)獲取用戶標籤的最有效方法

create_table "users", force: :cascade do |t| 
t.string "first_name" 
t.string "last_name" 
t.date  "dob" 
t.string "gender" 
t.datetime "created_at" 
t.datetime "updated_at" 
end 

create_table "email_accounts", force: :cascade do |t| 
t.integer "user_id" 
t.string "email" 
t.string "provider" 
t.datetime "created_at" 
t.datetime "updated_at" 
end 

create_table "account_subscriptions", force: :cascade do |t| 
t.integer "email_account_id", null: false 
t.integer "subscription_id", null: false 
t.datetime "created_at" 
t.datetime "updated_at" 
end 

create_table "subscriptions", force: :cascade do |t| 
t.string "email" 
t.datetime "created_at" 
t.datetime "updated_at" 
t.string "domain" 
end 

create_table "sub_tags", force: :cascade do |t| 
t.integer "subscription_id", null: false 
t.integer "tag_id",   null: false 
t.datetime "created_at" 
t.datetime "updated_at" 
end 

create_table "tags", force: :cascade do |t| 
t.string "name" 
t.datetime "created_at" 
t.datetime "updated_at" 
end 

我想看看哪個標籤通過這種關係應用到用戶。最有效的方法是什麼(渴望加載所有關係並循環遍歷它們,在Postgres中進行多級聯接等)?

+0

是在「訂閱」表列電子郵件的一個相同的「email_accounts」? –

+0

如果您在具有關係的圖像中顯示架構,則會更好! –

+0

@amit_saxena Nope,'email_accounts'電子郵件是個人電子郵件(例如:[email protected]),'訂閱'是您從簡訊中收到的(例如:[email protected]) – SomeSchmo

回答

1

假設你有合適的機型

user = User.find(user_id) 
tags = Tag.where(:id => SubTag.where(:subscription_id => AccountSubscription.where(:email_account_id => user.email_accounts.map{|e| e.id}).map{|a_s| a_s.subscription_id}).map{|s_t| s_t.tag_id}) 
tag_name = tags.map{|t| t.name} 

這應該做工精細給你有正確的索引。

+0

非常接近但會返回所有SubTag的列表,這是一個連接表。我希望自己的標籤(也不應該有'S''SubTag'末尾 – SomeSchmo

+0

編輯答案。 –

+0

真棒,謝謝! – SomeSchmo

相關問題