Rails searching a belongs_to relationship

时间:2016-04-12 00:43:04

标签: ruby-on-rails ruby

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?

1 个答案:

答案 0 :(得分:1)

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.