0

I've seen similar questions but nothing exactly like mine. I apologize if this is a duplicate - if it is, please refer me to answer(s).

I need to search orders by customer names, and the link between the two is users. Here are my models:

class Customer < ApplicationRecord
  belongs_to :user
end

class User < ApplicationRecord
  has_one :customer
  has_many :orders
end

class Order < ApplicationRecord
  belongs_to :user
end

I'm trying to search using:

@orders = Order.joins(:user).joins(:customers).where('last_name LIKE ?', name[0])

But I get the error message -

Can't join 'Order' to association named 'customers'; perhaps you misspelled it?

I'm sure I don't have the associations right, but I'm not sure how to do it. Thanks for any advice you can provide.

strivedi183
  • 4,749
  • 2
  • 31
  • 38
Steve
  • 89
  • 10

1 Answers1

3

Please try this.

Order.joins(user: [:customer]).where(customer: {last_name: name[0]})

I took help from this and this

Community
  • 1
  • 1
  • That did it. Thanks so much to you all. Just had to change customer: to customers: in the second reference @orders = Order.joins(user: [:customer]).where(customers: {last_name: name[0]}) – Steve Apr 24 '17 at 18:02
  • Good to hear that it worked. @Steve Will you accept this answer if it helped you in any way? Thanks. – Bittu Choudhary Apr 25 '17 at 06:48