按关联搜索 ActiveModel [英] ActiveModel search by association

查看:37
本文介绍了按关联搜索 ActiveModel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我见过类似的问题,但没有一个和我的完全一样.如果这是重复的,我很抱歉 - 如果是,请让我回答.

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])

但我收到错误消息 -

无法将订单"加入名为客户"的关联;也许你拼错了?

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

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.

推荐答案

请试试这个.

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

我从this这个

这篇关于按关联搜索 ActiveModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆