简体   繁体   中英

Rails 3 how to do a query with a habtm association

I need to dump a set of Awards into a instance variable:

@corp = Award.find(:all, :conditions => ["award.category_id = ?", "2" ])

Award <= => AwardsCategories <= => Categories

I am trying to find All the Awards that have a Category of X

The interesting piece I am noticing is that my Award.category_id is nil but the AwardsCategory.category_id and award_id are both set.

The error is returning is:

ActiveRecord::StatementInvalid in PagesController#award_cat

PGError: ERROR:  missing FROM-clause entry for table "award"
LINE 1: SELECT "awards".* FROM "awards"  WHERE (award.category_id = ...
                                                ^
: SELECT "awards".* FROM "awards"  WHERE (award.category_id = '2')

Any ideas and merry christmas

With a habm award doesn't need a category_id (after all, if it was used, how could an award have multiple categories?)

You need to join the award_categories table and put conditions on award_categories.category_id. Obviously if you have an actual category handy, you can just do

category.awards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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