Rails搜索查询关联模型

Rails搜索查询关联模型

本文介绍了Rails搜索查询关联模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在中,它们显示了我正在尝试实现的简单搜索。我有以下关联:

In railscast #37 they show a simple search I am trying to implement. I have the following association:

class Owner < ActiveRecord::Base
    has_many :dogs
end

class Dog < ActiveRecord::Base
    belongs_to :owner
end

狗模型有一个属性名称,所有者也是如此。我需要能够过滤狗列表,以便如果您键入 Fido(狗)或 Bob(所有者),则Fido将显示在列表中。当前设置搜索的方式如下:

The Dog model has an attribute "name" and so does the owner. I need to be able to filter a list of dogs so that if you type "Fido" (dog) or "Bob" (owner) Fido will show up in the list. Here is how the search is currently set up:

model dog.rb:

model dog.rb:

def self.search(search)
    if search
      find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
    else
      find(:all)
    end
end

这将仅返回与狗名匹配的搜索字词(所有者名称将被忽略)

this will return ONLY search terms matching the dog name (owner name is ignored)

我试图将其更改为以下形式:

I tried to change it to something like this:

  def self.search(search)
    if search
      find(:all, :conditions => ['name LIKE ? or owner.name LIKE ?', "%#{search}%", "%#{search}%"])
    else
      find(:all)
    end
  end

但是据说没有所有者列。如何更改搜索条件以能够同时搜索狗名和主人姓名?

However is says there is no owner column. How do I change the search condition to be able to search both dog name and owner name?

推荐答案

假设通过遵循Rails约定,您有名为 dogs 的表。 模型和所有者用于所有者模型。

Assuming that by following Rails convention you have tables named dogs for Dog model and owners for Owner model.

更新搜索方法如下:

  def self.search(search)
    if search
      joins(:owner).where('dogs.name LIKE ? or owners.name LIKE ?', "%#{search}%", "%#{search}%")
    else
      find(:all)
    end
  end

您需要在所有者表以访问 owners.name 字段

You need a join query between dogs and owners table in order to access owners.name field

这篇关于Rails搜索查询关联模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 06:57