簡體   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