简体   繁体   English

Rails:has_many活动记录查询

[英]Rails: has_many Active record query

I'm wondering how you would simulate a :has_many :through using an AR call. 我想知道您如何通过使用AR调用来模拟:has_many:。

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 贾斯汀

Assuming you have in your site.rb 假设您在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? 你确定它不会是更好地使用acts_as_treeawesome_nested_set呢?

Ultimately, I had to write the join instead since I can't specify a :source like I normally would if I created the relationship. 最终,我不得不编写连接,因为我无法像创建关系时那样通常指定:source。

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. 如果有人有更好的解决方案,我将在几天之内将答案保留。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM