Rails Search Query Associated Model

天大地大妈咪最大 提交于 2019-12-10 10:43:49

问题


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

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:

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?


回答1:


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

Update the search method as below:

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

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



来源:https://stackoverflow.com/questions/22970699/rails-search-query-associated-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!