我正在尝试重写这个旧的 Rails 2 东西,以便它可以与 Rails 3.2.1 一起使用:
Rails 2.2.2 查询重写
B2bPrivilege.find_by_sql("SELECT b2b_privileges.*, vendors.name AS vendor_name FROM b2b_privileges LEFT JOIN vendors ON vendors.id = b2b_privileges.vendor_id WHERE b2b_user_id = ?", current_user_id)
这就是我想出的,它创建了与上面 Rails 2.2.2 示例中看到的相同的 SQL,但它没有将 vendor.name 列引入存储的结果中,我不知道为什么。在数据库控制台中运行时生成的 SQL 确实有效,因此问题肯定与 Rails 有关。
B2bPrivilege.select("b2b_privileges.*, vendors.name AS vendor_name").joins('LEFT JOIN vendors ON vendors.id = b2b_privileges.vendor_id').where('b2b_user_id' => current_user_id)
来自 .inspect 的调试信息
B2bPrivilege Load (1.4ms) SELECT b2b_privileges.*, vendors.name AS vendor_name FROM "b2b_privileges" LEFT JOIN vendors ON vendors.id = b2b_privileges.vendor_id WHERE "b2b_privileges"."b2b_user_id" = 398
[
#<B2bPrivilege id: 1363, b2b_user_id: 398, vendor_id: 53, can_setup_instant_electronic_delivery: true, can_setup_purchase_orders: true, can_setup_advance_ship_notification: true, can_setup_xml_pushes: true>,
#<B2bPrivilege id: 1923, b2b_user_id: 398, vendor_id: 103, can_setup_instant_electronic_delivery: false, can_setup_purchase_orders: false, can_setup_advance_ship_notification: true, can_setup_xml_pushes: true>
]