Rails加入关联模型和父模型的查询

时间:2018-04-04 07:44:44

标签: ruby-on-rails ruby join

我有模型AutoCompanyAutoCompanyBranches

我想获取具有特定ID和特定分支国家/地区的汽车公司。我的查询

AutoCompany.joins(:auto_company_branches).where("auto_company_branches.country_id =? and id=?",country_id,id)

它出错

ActiveRecord::StatementInvalid: 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 'auto_company_branches WHERE (`auto_companies`.deleted_at IS NULL) AND (auto_comp' at line 1: SELECT `auto_companies`.`id` AS t0_r0, `auto_companies`.`name` AS t0_r1, `auto_companies`.`phone` AS t0_r2, `auto_companies`.`country_id` AS t0_r3, `auto_companies`.`city_id` AS t0_r4, `auto_companies`.`physical_address` AS t0_r5, `auto_companies`.`email` AS t0_r6, `auto_companies`.`website` AS t0_r7, `auto_companies`.`lat` AS t0_r8, `auto_companies`.`lng` AS t0_r9, `auto_companies`.`slug` AS t0_r10, `auto_companies`.`delta` AS t0_r11, `auto_companies`.`average_rating` AS t0_r12, `auto_companies`.`rating_count` AS t0_r13, `auto_companies`.`rating_sum` AS t0_r14, `auto_companies`.`locale` AS t0_r15, `auto_companies`.`visible` AS t0_r16, `auto_companies`.`created_at` AS t0_r17, `auto_companies`.`updated_at` AS t0_r18, `auto_companies`.`details` AS t0_r19, `auto_companies`.`logo` AS t0_r20, `auto_companies`.`cars_url` AS t0_r21, `auto_companies`.`other_lang_key` AS t0_r22, `auto_companies`.`is_featured` AS t0_r23, `auto_companies`.`enhance_page` AS t0_r24, `auto_companies`.`conversion_id` AS t0_r25, `auto_companies`.`phone_conversion_label` AS t0_r26, `auto_companies`.`email_conversion_label` AS t0_r27, `auto_companies`.`is_verified` AS t0_r28, `auto_companies`.`admin_user_id` AS t0_r29, `auto_companies`.`deleted_at` AS t0_r30, `auto_company_translations`.`id` AS t1_r0, `auto_company_translations`.`auto_company_id` AS t1_r1, `auto_company_translations`.`name` AS t1_r2, `auto_company_translations`.`locale` AS t1_r3, `auto_company_translations`.`physical_address` AS t1_r4, `auto_company_translations`.`details` AS t1_r5, `auto_company_translations`.`created_at` AS t1_r6, `auto_company_translations`.`updated_at` AS t1_r7 FROM `auto_companies` LEFT OUTER JOIN `auto_company_translations` ON `auto_company_translations`.`auto_company_id` = `auto_companies`.`id` auto_company_branches WHERE (`auto_companies`.deleted_at IS NULL) AND (auto_company_branches.country_id =1 and  id=3242)

1 个答案:

答案 0 :(得分:0)

尝试以下查询

AutoCompany.joins(:auto_company_branches).where("auto_company_branches.country_id =? and id=?",country_id,id)

在您的查询中,您错过了使用的联接,因此使用joins(:auto_company_branches)代替where(:auto_company_branches)