Topic: Active Record Querying HABTM

I am new to rails and stuck on one Querying issue. Here is the
situation.

Model: Category
class Category < ActiveRecord::Base
       has_and_belongs_to_many :postings
       has_and_belongs_to_many :volunteers
end

Model: Posting
class Posting < ActiveRecord::Base
       has_and_belongs_to_many :categories
end

Model: Volunteer
class Volunteer < ActiveRecord::Base
       has_and_belongs_to_many :categories
end

-------
Now Here is the problem I am trying to solve

I want to find out all the postings of the categories that the volunteer is interested in. The volunteer might be interested in more than one categories and posting might be assigned more than one categories.

Here is the basic pseudocode

vol=Volunteer.find 1
vol_cats=vol.categories
foreach(vol_cat in vol_cats)
{
  postings=postings + vol_cat.postings
}

Please help me to implement this on rails

Thank you

Last edited by sarojsigdel (2012-06-11 11:32:47)

Re: Active Record Querying HABTM

You can try as follows, but I'm not sure:

Category.joins(:postings, :volunteers)

may be you will have to 'tune' it by adding some 'distinct', 'select', etc.

See more examples at Rails guides-Query interface

Last edited by Javix (2012-06-12 09:11:20)

Re: Active Record Querying HABTM

In volunteer class I add

has_many postings, :through=> :categories, uniq=> :true

and by calling
Volunteer.find(1).postings

fixed the problem

http://stackoverflow.com/questions/1098 … ails-3-2-1

Last edited by sarojsigdel (2012-06-13 23:30:51)