Justin
Justin

Reputation: 641

Rails: has_many Active record query

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

Upvotes: 1

Views: 1574

Answers (2)

Justin
Justin

Reputation: 641

Ultimately, I had to write the join instead since I can't specify a :source like I normally would if I created the relationship.

Category.joins("JOIN cat_sub_links ON cat_sub_links.subcategory_id=categories.id").where(: cat_sub_links => {:site_id => @site_ids})

I'll leave the answer out for a few days if anyone has a more elegant solution.

Upvotes: 0

Luke
Luke

Reputation: 1649

Assuming you have in your site.rb

class Site < AR
  has_many :cat_subcat_links
  has_many :subcategories, :through => :cat_subcat_links
  has_many :categories, :through => :cat_subcat_links
end

Couldn't you just do:

Site.find([your_site_id]).categories

Also:

Site.find([your_site_id]).subcategories

Also just a thought; are you sure it wouldn't be better to use acts_as_tree or awesome_nested_set instead?

Upvotes: 1

Related Questions