具有多个且属于RAILS 3的复杂查询
||
我试图在控制器中进行查询,以获取具有类别ID的供应商列表。
我有这样的模型设置。
class Supplier < ActiveRecord::Base
has_and_belongs_to_many :sub_categories
end
class Category < ActiveRecord::Base
has_many :sub_categories
end
class SubCategory < ActiveRecord::Base
belongs_to :category
has_and_belongs_to_many :suppliers
end
供应商可以具有一个子类别下的许多子类别。这样我就可以抓住供应商的类别。
@supplier.sub_categories.first.category.name
这将返回供应商所属的类别,因为他们必须至少具有1个子类别,然后再链接到该类别。
我想做的是通过传递一个category_id,我希望返回该类别下的所有供应商。
我把它写成这样,但似乎没有用。
@category = Category.find(params[:category_id])
@suppliers = Supplier.where(\'sub_category.first.category.id = ?\', @category.id)
我得到以下SQL错误
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'.id = 20)\' at line 1: SELECT `suppliers`.* FROM `suppliers` WHERE (sub_category.first.category.id = 20)
没有找到相关结果
已邀请:
1 个回复
徐百晴墓斜
正如Caley Woods所建议的那样,应将其放置在Supplier模型中作为范围:
然后称为