简体   繁体   中英

Rails searching a belongs_to relationship

In my application I have a Property and Customers model. Property has_one :customer and Customer belongs_to :property . Property has an address column of type string.

I am trying to allow users to search Customers by the address of the property it belongs to.

# 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

Doing this doesn't work:

  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

What is the best way to accomplish this?

You need to use a "join."

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

In SQL terminology this is called an "inner join."

Here is the Rails Guide on joining tables .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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