I'm developing an marketplace app where sellers can list items to sell. On the listing show page, I developed a widget called "other items from this seller". I use the below query to pull these items into the view.
Listing.where(:user_id => @listing.user)
This works but it includes the activerecord. Since this is a widget for "other items" I want to exclude the listing whose page the user is currently on. Note that the "user_id" field in the listing model is the sellers user id.
How would I modify this? I tried the below but it gives me an error saying it expects an "=>".
Listing.where(:user_id => @listing.user, :id != @listing.id)
How about simply using array parameter to where
:
@listing.user.listings.where(["id != ?", @listing])
OR ( better performance )
Listing.where(["user_id = ? AND id != ?", @listing.user_id, @listing.id])
为了完整起见,如果您使用的是rails 4.x,则可以使用.where.not
Listing.where(user_id: @listing.user_id).where.not(id: @listing.id)
除了RAJ的答案,您还可以链接两个子句以进行一个查询
Listing.where(:user_id => @listing.user).where("id != ?", @listing.id)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.