0

我有以下DB結構如何添加條件has_many關聯

任務

id name parent_id 
1 Abc nil 
2 Pqr 1 

評論

id task_id body 
1 1  This is sample comment 
2 1  This is another sample comment 

task.rb

has_many :comments 

comment.rb

belongs_to :task 

我的要求是有一個協會,這樣的父母以及兒童我應該得到父母的意見,即上述兩個任務我應該得到['這是樣品評論','這是另一個樣本評論']作爲小孩任務不會有任何評論。

我想是這樣,但之後它不工作

task.rb

has_many :comments, -> (o) { where(comments: {task_id: [o.id, o.parent_id]}) } 
+0

_but不WORK_ - 有什麼錯誤? – 31piy

回答

1

因爲你的新病症與來自has_many默認的一個組合它不工作。您可以使用unscope方法來取消默認條件:

has_many :comments, -> (task) { unscope(:where).where(comments: {task_id: [task.id, task.parent_id]}) } 

注意:這將打破評論模型default_scope如果有一個。

在Rails5你將能夠OR條件添加到默認的:

has_many :comments, -> (task) { or(comments: {task_id: task.parent_id}) } 
+0

我嘗試過'rewhere',但它仍然結合了默認值 – Salil

+0

你是對的。這沒有用。我需要更多時間來尋找解決方案 – chumakoff

+0

在這裏,你去!更新了答案。 – chumakoff