2017-05-04 36 views
0

我想弄清楚如何根據特定規範爲我所呈現的JSON包含關聯模型。這是我到目前爲止有:包括相關模型以基於條件呈現json

render json: @colleges, include: :sports 

@colleges是高校的集合,以及所有相關的運動都包括在內。

但是,我希望只有在屬於當前用戶的情況下才能包含其他關聯模型

因此,例如,我可以獲得屬於大學和用戶的收藏夾Favorite.where(college: @college).where(user: current_user)

有沒有辦法將屬於current_user和每個大學的收藏夾包含到此呈現中?

+0

讓我們假設用戶已登錄,這是否會返回正確的結果? '@ students.joins(:favorite).where(user:current_user)' –

+0

這給了我正確的結果,但是我想呈現所有大學,而不管用戶最愛是否與它關聯。但是如果存在,我想包含關聯的最愛。因此,如果用戶的最愛不存在,那麼json會看起來像'{college:{name:'foo',location:'bar',sports:{name:'basketball'}}'。如果它確實存在,它會看起來像'{college:{name:'foo',位置:'bar',sports:{name:'basketball'},收藏夾:{user_id:45}}' – Doug

回答

0

你可以嘗試這樣的事情使用條件範圍:

在模型中

scope :favorite_for, -> (user) { joins(:favorite).where(user: current_user) if user } 

在你的控制器

@colleges = College.favorite_for(current_user).all # or where() or whatever you like.. 

希望它可以幫助..