I’m wondering how you would simulate a :has_many :through using an AR call.
Ultimately, I’m trying to find the subcategories that belong to a site, not the top level categories, which is what the query currently gives me.
Models:
class Categories < AR
:has_many :subcategories, :through => :cat_subcat_links
:has_many :cat_subcat_links
end
Linking Model:
class CatSubcatLinks < AR
:category_id
:subcategory_id
:site_id
end
At the moment, if I want to get which categories belong to a particular site I perform:
Category.joins(:cat_subcat_links).where(:cat_subcat_links => {:site_id => 1})
The query that returns:
SELECT `categories`.* FROM `categories` INNER JOIN `cat_sub_links` ON `cat_sub_links`.`category_id` = `categories`.`id` WHERE `cat_sub_links`.`site_id` = 1
The problem is
`cat_sub_links`.`category_id` = `categories`.`id`
I need it to say
`cat_sub_links`.`subcategory_id` = `categories`.`id`
That will cause the query to return me the subcategories. Thoughts?
Thanks in advanced,
Justin
Ultimately, I had to write the join instead since I can’t specify a :source like I normally would if I created the relationship.
I’ll leave the answer out for a few days if anyone has a more elegant solution.