轨道:从数组填充对象 [英] RAILS: fill Object from Array

查看:62
本文介绍了轨道:从数组填充对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用任意SQL语句从查询中填充数组

Array is filled from query using arbitrary SQL statement

@myarray = myObject.find_by_sql(sql)

SQL的设计方式是,每个 myarray 项都具有相同的字段作为 myObject 模型,例如

SQL is designed in such way that each myarray item has same fields as myObject Model, e.g.

\#{myObject value: 100, day: 2013-06-15}

理想情况下,我希望拥有myObjects数组

Ideally, I would like to have array of myObjects


  1. 已填充数组中的数据;

  2. 可访问html;

  3. 未保存到数据库。

有可能吗?

推荐答案

从文档中获取 ActiveRecord :: Querying#find_by_sql


执行针对您的数据库的定制SQL查询,并返回所有结果。结果将作为数组返回,其中请求的列封装为您从中调用此方法的模型的属性。如果调用Product.find_by_sql,则结果将返回到具有您在SQL查询中指定的属性的Product对象中。

Executes a custom SQL query against your database and returns all the results. The results will be returned as an array with columns requested encapsulated as attributes of the model you call this method from. If you call Product.find_by_sql then the results will be returned in a Product object with the attributes you specified in the SQL query.

因此我不太了解您的问题。 AR会尝试将查询返回的字段映射到对象字段。

如果将其分配给对象变量,则可以在视图中访问。

除非执行以下命令之一,否则记录永远不会保存。执行保存的方法。

So I don't really understand your question. AR will try to map fields returned from query to object fields.
It is accessible in views if you assign it to object variable.
Records never got saved unless you execute one of the methods that perform save.

编辑:

请记住,除非AR否则无法将结果集映射到记录您返回id列。

Remember that AR will not be able to map resultset to records unless you return id column.

这篇关于轨道:从数组填充对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆