Search from has_many?


#1

Hi,

In my application I have bots that have_many packs. Usually there is
just a big list with each bot and its packs. I’d like to add a filter
that shows only bots with packs matching a keyword (and only the
matching packs from those bots). I have sincerely no idea how to do this
properly.

The following works, but I doubt it’s really the proper way of doing
this:

class Bot < ActiveRecord::Base
has_many :packs, :order => ‘number’
def self.search(search)
has_many :packs, :order => ‘number’, :conditions => [‘name LIKE ?’,
search]
end
end

Any help will be much appreciated!

Regards,
Iikka


#2

Your example is a bit odd, are you trying to find all the packs of a bot
which match the given name… ? If so:

class Bot < ActiveRecord::Base
has_many :packs, :order => ‘number’

def search_packs(keyword)
packs.find(:all, :conditions => [‘name like ?’, “%#{keyword}%”])
end
end

Then you can do … Bot.find(:first).search_packs(‘mine’). Or if you
just want to find all the Pack objects by a certain name, do:

Pack.find(:all, :conditions => [‘name like ?’, “%wonka%”])

Cheers, -Jonny.

this:

class Bot < ActiveRecord::Base
has_many :packs, :order => ‘number’
def self.search(search)
has_many :packs, :order => ‘number’, :conditions => [‘name LIKE ?’,
search]
end
end


#3

Thanks for your answer!

Jonathan V. wrote:

Your example is a bit odd, are you trying to find all the packs of a bot
which match the given name… ?

I’m trying to find all bots with packs that match the given name. For
these bots only the matching packs should be returned.

I hope this makes it a bit clearer.

Regards,
Iikka