James
James

Reputation: 1887

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?

Upvotes: 0

Views: 163

Answers (1)

sixty4bit
sixty4bit

Reputation: 7926

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.

Upvotes: 1

Related Questions