Can Two Active Record Results be Added?

I have an sql with some inputs,notably a date. For that date I run
the sql and get a result

@result = Model.find_by_sql(sql)

What I want is to have eight versions of this (different dates in the
sql) and then combine all the results and pass them back once to the
view. Is that possible?

On Jul 24, 8:09 am, Jorg L. [email protected] wrote:

I have an sql with some inputs,notably a date. For that date I run
the sql and get a result

@result = Model.find_by_sql(sql)

What I want is to have eight versions of this (different dates in the
sql) and then combine all the results and pass them back once to the
view. Is that possible?

Yes it is

If you can come up w/SQL that will return > 1 record, find_by_sql (like
all the other find* methods) should return an array of instances of your
model w/out any extra work on your part.

Huh–can you not pass a “exec my_cool_sproc” to find_by_sql?

But if you’ve just got a set of dates to cycle through, can’t you just
stash those in an in() list? In fact, I wouldn’t be surprised if you
could just pass an array of DateTimes to Model.find_by_my_date_field. I
know the plain Model.find will take an array of IDs…

In this case that would be a lot harder than creating the instances
multiple times and adding them together. Though it’s likely more
efficient to do it all on the backend, doing procedural logic in SQL
isn’t very clean. If ActiveRecord supported stored procs it would
make it easier. Of course some people think all logic, even data
logic,belongs outside the data layer.

exec doesn’t work in DB2. I can pass a call. That seems to work but
not if there’s output parms “uncaught throw `Column information cannot
be retrieved:” Something to explore a little later. One could also
write a UDF.

An in list would work the way you describe but in this case it’s
basically a concatenation of the sql statement with each different
date. On 7/28 5 employees might be on PTO on 8/4 maybe 7. Each date
needs to be tested.

Ahhh–okay. I get it now. Well, at least the ruby isn’t too painful to
write–something like:

def self.find_unavailable_by_dates(array_of_dates)
results = []
array_of_dates.uniq!.sort!
array_of_dates.each do |this_date|
sql = “blah blah blah #{this_date}”
results << self.find_by_sql(sql)
end
results
end

Should do it I’d think…

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs