按关联搜索 ActiveModel

ActiveModel search by association

我见过类似的问题,但与我的完全不同。如果这是重复的,我深表歉意 - 如果是,请让我回答。

我需要按客户名搜索订单,两者之间的link是users。这是我的模型:

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' 加入名为 'customers' 的协会;也许你拼错了?

我确定我没有正确的关联,但我不知道该怎么做。感谢您提供的任何建议。

请试试这个。

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

我得到了this and

的帮助