开发者

Complex Query with Has many and belongs to for RAILS 3

I am trying to do a QUERY in my controller to get a list of suppliers with a category ID.

I have my models set up like this.

  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

A supplier can have Many sub_categories that are under one single category. So i can grab the category of a supplier by doing this.

  @supplier.sub_categories.first.category.name

This returns the category that the supplier comes under because they have to have at least 1 sub category which is then linked to a category.

What i am trying to do is by passing a category_id i wish to return all suppliers that come under that category. I had it written like this but it doesnt seem to be working.

  @category = Category.find(params[:category_id])
  @suppliers = Supplier.where('sub_category.first.category.id = ?', @category.id)

i get the following sql error

  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)


Well, that's certainly an sql error. The stuff inside the where() call gets translated directly to SQL, and that's not sq;l. :)

You need to join tables together. I'm assuming there's a sub_category_suppliers table that completes the habtm association. (BTW, I much prefer to use has_many :through exclusively)

I think it would be something like this:

Supplier.joins(:sub_category_suppliers => :sub_categories).
         where('sub_categories.category_id =?', @category.id).
         group('suppliers.id')

As Caley Woods suggested, this should be placed in the Supplier model as a scope:

scope :by_category, lambda { |category_id|
  joins(:sub_category_suppliers => :sub_categories).
         where('sub_categories.category_id =?', category_id).
         group('suppliers.id')
}

and then called as Supplier.by_category(@category.id)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜