find_by_sql 不适用于 Rails 3.1.3
我正在 Ruby on Rails 3.1.3 中编写一个相当复杂的查询,并且使用 find_by_sql。
但我注意到一个非常奇怪的行为,即使我使用 find_by_sql 进行非常简单的查询。
这是一个简单的例子:
假设我有两个模型和相关表:
Model 1: Company
Table 1: companies
fields: id, name, address
| id | name | address |
+----+------+-----------------+
| 1 | ACME | Bond street, 56 |
并且:
Model 2: Employee
Table 2: employees
fields: id, name, age
| id | name | age |
+----+------+-----+
| 1 | Fred | 56 |
| 2 | Adam | 27 |
这就是发生的情况;如果我写:
Company.find_by_sql("SELECT * FROM `employees`")
我得到:
Company Load (0.3ms) SELECT * from `employees`
=> [#<Company id: 1, name: "Fred">, #<Company id: 2, name: "Adam">]
我只得到姓名与公司中的姓名匹配的员工的字段(即,字段年龄缺失)! 根本没有@attributes。
这是一个错误吗?有人可以帮我吗?
I am writing a quite complex query in Ruby on Rails 3.1.3, and I am using find_by_sql.
But I noticed a very strange behaviour, even if I use find_by_sql with very simple queries.
Here is a simple example:
Let' say that I have two models and related tables:
Model 1: Company
Table 1: companies
fields: id, name, address
| id | name | address |
+----+------+-----------------+
| 1 | ACME | Bond street, 56 |
and:
Model 2: Employee
Table 2: employees
fields: id, name, age
| id | name | age |
+----+------+-----+
| 1 | Fred | 56 |
| 2 | Adam | 27 |
Here is what happens; if I write:
Company.find_by_sql("SELECT * FROM `employees`")
I get:
Company Load (0.3ms) SELECT * from `employees`
=> [#<Company id: 1, name: "Fred">, #<Company id: 2, name: "Adam">]
I only get the fields of employees whose names match the ones in companies (i.e., the field age is missing)!
No @attributes at all.
Is it a bug? Can anyone please help me?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
控制台使用漂亮的打印来输出查询返回的任何实例的数据。漂亮的打印是由
ActiveRecord
根据与该特定模型关联的列在类中自动实现的,因此不会显示不属于该特定模型的属性。但这并不意味着属性没有加载到实例中。漂亮的印刷只是没有显示它们,但它们仍然存在。
因此,如果您这样做:
根据您的示例,您应该仍然会得到
56
。The console uses pretty printing to output data from any instances returned by the query. Pretty printing is implemented automatically in the class by
ActiveRecord
according to the columns associated with that particular model, and won't therefore display attributes that do not belong to that particular model.That does not mean however the attributes were not loaded into the instances. Pretty printing is just not showing them, but they are still there.
So if you just do:
You should still get
56
according to your example.尝试:
try:
如果您从
employees
表中进行选择,您将需要使用 Employee 模型。试试这个
If you're selecting from the
employees
table you will want to use the Employee model.Try this instead