Forum: Ruby on Rails Search from has_many?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
D554cce20bc02d34e417693e8fe7fee3?d=identicon&s=25 Iikka Niinivaara (mebe)
on 2006-02-11 00:56
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
337cdd270761e0e6f4356de45b04d388?d=identicon&s=25 Jonathan Viney (jonny)
on 2006-02-11 15:17
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
>
D554cce20bc02d34e417693e8fe7fee3?d=identicon&s=25 Iikka Niinivaara (mebe)
on 2006-02-11 17:18
Thanks for your answer!

Jonathan Viney 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
This topic is locked and can not be replied to.