繁体   English   中英

Rails搜索一个归属关系

[英]Rails searching a belongs_to relationship

在我的应用程序中,我有一个属性和客户模型。 属性has_one :customer和Customer belongs_to :property 属性具有一个字符串类型的地址列。

我试图允许用户通过其所属属性的地址搜索“客户”。

# customer.rb
class Customer < ActiveRecord::Base
  belongs_to: property

  def self.search(search, user)
    if search
      where('full_name LIKE ?', "%#{search}%").where(user: user)
    else
      where(user: user)
    end
  end
end

这样做不起作用:

  def self.search(search, user)
    if search
      where('full_name LIKE ? OR property.address LIKE ?', "%#{search}%", "%#{search}%").where(user: user)
    else
      where(user: user)
    end
  end

做到这一点的最佳方法是什么?

您需要使用“联接”。

  def self.search(search, user)
    if search
      joins(:property).where('properties.address LIKE ?', "%#{search}%").where(user: user)
    else
      where(user: user)
    end
  end

在SQL术语中,这称为“内部联接”。

这是有关联接表Rails指南

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM