ActiveModel按关联搜索

我见过类似的问题但没有完全像我的。 如果这是重复,我道歉 – 如果是,请转介我回答。

我需要按客户名称搜索订单,两者之间的链接是用户。 这是我的模特:

class Customer < ApplicationRecord belongs_to :user end class User < ApplicationRecord has_one :customer has_many :orders end class Order < ApplicationRecord belongs_to :user end 

我正在尝试搜索:

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

但我收到错误信息 –

无法将“订单”加入名为“客户”的协会; 也许你拼错了吗?

我确信我没有正确的协会,但我不知道该怎么办。 感谢您提供的任何建议。

请试试这个。

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

我从这里得到了帮助