ActiveModel按关联搜索

时间:2017-04-24 12:36:20

标签: ruby-on-rails rails-activerecord 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])

但我收到错误消息 -

无法加入&#39;订购&#39;以名为&#39;客户&#39 ;;也许你拼错了吗?

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

1 个答案:

答案 0 :(得分:3)

请试一试。

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

我从thisthis

获得了帮助
相关问题