2016-04-12 19 views
0

Uygulamamda Mülk ve Müşteriler modelim var. Mülkiyet has_one :customer ve Müşteri belongs_to :property. Mülkte bir karakter dizesi dizesi var.Bir ilişkiyi arama rayları

Kullanıcıların, Müşterileri ait olduğu mülkün adresine göre aramalarına izin vermeye çalışıyorum.

# 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 

Bu işe yaramazsa yapmak:

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 

Bunu başarmanın en iyi yolu nedir?

cevap

1

"Birleştirme" kullanmanız gerekir.

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

SQL terminolojisinde buna "iç birleştirme" denir.

İşte Rails Guide on joining tables.