2011-02-10 14 views
1

我需要一些幫助建立一個表,然後用Rails 3構建具有User_ids的字段的表,然後查詢特定USER_ID

及彼從該表數據公司的擊穿:

模型 - 在這裏,他們參與3個車型有:

  • 主題有許多參與者
  • 參與者屬於線程
  • 用戶

活動表:

id | thread_id | participants 

記錄示例會看起來像:

1 | 300 | 3,1,5,67,13 
2 | 333 | 3,12 
3 | 433 | 1,12 
4 | 553 | 1,12, 67 

,參與者,是user_ids的名單,如果有更好的方式來存儲user_ids請讓我知道。我還沒有建立這個。

填充活動表後。然後我希望能夠查詢以下內容: 選擇參與者字段中包含67的participant_id的所有活動記錄。

我希望以上內容清楚,如果不是,請讓我知道。想法?思考?建議。

感謝

+0

有人嗎?混淆問題還是? – AnApprentice 2011-02-10 03:26:05

回答

5

雖然這是很有誘惑力的多個值存儲在列,它總是與別人受到傷害結束。你最好建立一個連接表來關聯這些模型。

例如,你可以這樣做:

class DiscussionThread < ActiveRecord::Base 
    has_many :participations 
    has_many :participants, :through => :participations 
end 

class Participation < ActiveRecord::Base 
    belongs_to :discussion_thread 
    belongs_to :participant, :class_name => "User", :foreign_key => :user_id 
end 

class User < ActiveRecord::Base 
    has_many :participations 
    has_many :dicussion_threads, :through => :participations 
end 

這就給了你三個表:

table: discussion_threads 
columns: id 

table: participations 
columns: id | discussion_thread_id | user_id 

table: users 
columns: id 

在其中找到一個用戶正在參與線程,只是做:

@user.discussion_threads 

並找到參與線程的用戶:

@discussion_thread.participants 

注:Thread是Ruby的保留字,所以我給它改名DiscussionThread

編輯

心態呈現出如何序列ID,然後查詢的一個陣列的例子反對他們?

你醒來在半夜,和一個陌生的強制的力量下你去你的計算機,並創建這個遷移:

rails g model Abomination horror_ids:text 

和型號:

class Abomination < ActiveRecord::Base 
    serialize :horror_ids 
end 

你測試它以確保它可以存儲陣列:

@abomination = Abomination.create(:horror_ids=>[2,33,42]) 
@abomination.horror_ids # => [2,33,42] 

所以 什麼?你知道幕後的Rails背後將其轉換爲YAML,它看起來像這樣:

---\n 
- 2\n 
- 33\n 
- 42\n 

由奇怪的催促下再次被迫的,你想知道「我怎麼能搜索存儲在該列的特定ID?」。那麼,這只是一個字符串,對吧?你知道如何尋找,在一個文本字段:

cthulhu = 33 
Abomination.where(["horror_ids LIKE '%- ?\n%'",cthulhu]).first 

隨着越來越多的恐懼,你意識到有人可能會碰到這個絆倒,並認爲它實際上是一個好主意。它必須被摧毀!但你無法鍵入rm -rf *,而不是怪力,使你考慮怪癖邪神開發商的未來 盲目的跟隨者可能需要知道的,比如

@abomination = Abomination.create 
@abomination.horror_ids # => nil 

@abomination = Abomination.create(:horror_ids=>[]) 
@abomination.horror_ids # => [] 

@abomination = Abomination.create(:horror_ids=>"any string value can go here") 
@abomination.horror_ids # => "any string value can go here" 

而事實上,串行數據遭到損壞當柱大小太小而無法容納這一切時。

你做了最後一次努力,把電源線拉出來,但已經太晚了,已經控制了你的小竅門,瘋狂的意識在StackOverflow上發佈了代碼,讓整個世界都看到了。最後你陷入困擾的睡眠。第二天,意識到你所犯下的錯誤,你永遠放棄編碼,成爲會計師。

道德

不要這樣做

+0

謝謝我在大多數情況下都同意連接表。但在我的情況下,我正在建立一個臨時數據的新聞源,並且需要避免數據庫命中。這就是爲什麼我要走這條路。非常類似於FB或Twitter等大型網絡。有關如何使上述可能的任何想法? – AnApprentice 2011-02-10 06:54:34

相關問題