0

我正在尝试重写这个旧的 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>
]
4

2 回答 2

1

事实证明,加入的内容在那里它只是不输出到控制台,只是主要关系。如果您在控制台窗口中查看输出,我认为控制台输出仅反映/检查返回的根级别对象。

当我调试使用联接的查询时,这对我来说是一个问题

于 2013-03-13T17:43:52.020 回答
0

B2bPrivilege.joins('LEFT JOIN  vendors ON vendors.id = b2b_privileges.vendor_id').
  where(:b2bprivileges => {'b2b_user_id' => current_user_id} ).
  select("b2b_privileges.*, vendors.name AS 'vendor_name'").first.vendor_name
于 2013-03-12T20:36:07.950 回答