0

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 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Michael, indeed. You are right. I got it into the myObject. My project relates to show myarray in calendar_for. Thank you. Nik
When it is called from calendar_for I get this reply: No route matches {:action=>"show", :controller=>"myobject", :id=>#<MyObject value: 100.0, day: "2013-06-14 00:00:00">}. In my route.rb I have made proper match to myobjects/index_calendar.html.erb, however, "show" gets called and entire MyObject is assigned to :id.
@nikz problem is not that you don't have id in MyObject so Rails doesn't know how to create link!
addition of incrementally increasing 'id' to the select statement has solved the problem. Search for solution: I have booked fake booking_day record into DB, checked its structure via puts booking_days[0].inspect and compared it to my virtually created object from SQL. 'id' was missing. Thank you very much for directions.
SO, could you approve my answer? :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.