簡體   English   中英

在我使用它在Rails中檢索關系之后,將字段添加到“ .where”語句中

[英]Add a field to a “.where” statement after I use it to retrieve a relationship in Rails

我目前正在嘗試從用戶的朋友(數組)和用戶本身獲取所有列表。

我努力了:

 ids = current_user.friends << current_user
 @listings = Listing.where(:user_id => ids)

但是當我使用這個heroku崩潰。 我想得到的根本是

@listings = Listing.where(:user_id => current_user.friends OR :user_id => current_user)

我們怎樣才能做到這一點?

您可以通過兩種方式來實現。 通過ID數組或對象數組本身。 不是活動的記錄對象。 因為如果使用活動記錄對象,它不能正確附加對象。

考慮的朋友也來自用戶表。

ids = current_user.friends.to_a << current_user
@listings = Listing.where(:user_id => ids)

要么

ids = current_user.friends.pluck(:id).to_a << current_user.id
@listings = Listing.where(:user_id => ids)

如果friends id從具有一對多關聯的另一個稱為friends的表中獲取,那么。

ids = current_user.friends.pluck(:user_id).to_a << current_user.id
@listings = Listing.where(:user_id => ids)

您需要傳遞ID數組,試試看

@listings = Listing.where("user_id IN (?)", current_user.friends.pluck(:user_id))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM