Rails控制台不同于MySQL结果

时间:2014-01-21 20:49:24

标签: mysql ruby-on-rails ruby join

我在使用带有Rails的LEFT OUTER JOIN时遇到问题。我想我的Ruby代码已经关闭,但是当我将它输入rails console时,我得到一个结果,当我复制生成的MySQL时,我得到了另一个结果。 rails console中缺少整个列(值)。为什么SQL完全相同但我得到的结果不同?理想情况下,我希望结果包含值列。一如往常,任何帮助都将不胜感激。

Rails控制台响应

2.0.0-p353 :023 > SecurityItem.joins("LEFT OUTER JOIN  security_role_permissions ON security_role_permissions.security_item_id = security_items.id  AND security_role_permissions.role_id ='1'").select("security_items.name, security_role_permissions.value")

 SecurityItem Load (0.7ms)  SELECT security_items.name, security_role_permissions.value FROM `security_items` LEFT OUTER JOIN security_role_permissions ON security_role_permissions.security_item_id = security_items.id AND security_role_permissions.role_id ='1

=> #<ActiveRecord::Relation 
[#<SecurityItem id: nil, key: "ChangePassword", name: "Change Password">, 
 #<SecurityItem id: nil, key: "AddUsers", name: "Add Users">, 
 #<SecurityItem id: nil, key: "UpdateUsers", name: "Update Users">, 
 #<SecurityItem id: nil, key: "DeleteUsers", name: "Delete Users">]> 

MySQL响应

mysql>  SELECT security_items.name, security_role_permissions.value FROM `security_items` LEFT OUTER JOIN security_role_permissions ON security_role_permissions.security_item_id = security_items.id AND security_role_permissions.role_id ='1';

+-----------------+-------+
| name            | value |
+-----------------+-------+ 
| Change Password |     1 |
| Add Users       |  NULL |
| Update Users    |  NULL |
| Delete Users    |  NULL |
+-----------------+-------+

1 个答案:

答案 0 :(得分:1)

只有SecurityItem类中的属性出现在返回结果中。但是,您可以通过“属性”方法访问联接表中的属性。

security_items = SecurityItem.joins("LEFT OUTER JOIN  security_role_permissions 
ON security_role_permissions.key = security_items.key  AND
security_role_permissions.role_id ='1'").select("security_items.name, 
security_items.key, security_role_permissions.permission")

security_items.each { |security_item| puts security_item.attributes['permission'] }