Reputation: 3216
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)
Upvotes: 1
Views: 375
Reputation: 4959
For completeness, if you are using rails 4.x you could use .where.not
Listing.where(user_id: @listing.user_id).where.not(id: @listing.id)
Upvotes: 2
Reputation: 9747
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])
Upvotes: 3
Reputation: 2171
In addition to RAJ's answer, you can chain the two clauses to make one query
Listing.where(:user_id => @listing.user).where("id != ?", @listing.id)
Upvotes: 0