Moosa
Moosa

Reputation: 3216

Exclude Rails ActiveRecord from query

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

Answers (3)

ChrisBarthol
ChrisBarthol

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

RAJ
RAJ

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

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

Related Questions