Where clause with includes not working

Joined
Sep 29, 2023
Messages
2
Reaction score
0
my where clasue with includes isn't working, it's returning all records instead of the expected filter
@items=Item.includes:)sales).where("unit_price is not null and item_type_id=? and title like ?, @item_type_id, params[:search] and :sales => { :item_id => nil }").order:)title)
 
Joined
Jul 4, 2023
Messages
589
Reaction score
78
BTW,
Ruby:
@items = Item.includes(:sales)
             .where("unit_price is not null and item_type_id=? and title like ?, @item_type_id, params[:search] and :sales => { :item_id => nil }")
             .order(:title)
 
Last edited:
Joined
Sep 29, 2023
Messages
2
Reaction score
0
I think it's the way I'm rendering my partial I'm causing the index action to run instead of display the results of the search action through the _items.html.erb partial
 
Joined
Apr 8, 2025
Messages
2
Reaction score
0
left_outer_joins(:sales): This ensures that all Item records are included, even those without associated sales. Use this if you want items even if they don't have any sales that match the criteria. If you only want items that HAVE sales records, use joins(:sales)

where.not(sales: { item_id: nil }): This accurately filters for Item records that have associated sales with a non-null item_id.

Ruby:
@items = Item.left_outer_joins(:sales)
            .where(unit_price: nil) # changed from 'is not null' based on comment
            .where(item_type_id: @item_type_id)
            .where("title LIKE ?", "%#{params[:search]}%")  # Sanitize search input!
            .where.not(sales: { item_id: nil }) 
            .order(:title)

includes vs. joins: If you're not actually using data from the sales table in your view, you might not need includes (eager loading) and a simple joins (to perform the filtering) might be sufficient and faster. preload is also an option in Rails for eager loading. Choosing between includes, preload, and joins depends on the context of how you are using the data and the complexity of your associations.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,260
Messages
2,571,038
Members
48,768
Latest member
first4landlord

Latest Threads

Top