RAILS: fill Object from Array

寵の児 提交于 2019-12-11 15:07:45

问题


Array is filled from query using arbitrary SQL statement

@myarray = myObject.find_by_sql(sql)

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}

Ideally, I would like to have array of myObjects

  1. Filled with data from Array;
  2. Accessible for html;
  3. Not saved to the database.

Is it at all possible?


回答1:


From docs for ActiveRecord::Querying#find_by_sql:

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.

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.

EDIT:

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



来源:https://stackoverflow.com/questions/17264807/rails-fill-object-from-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!