Thnak you Matthew, I know SQL a bit :), but what to do if field is
much more complicated, for ex. I have few more complex fields in my
Order model:
def number_of_produced_items
total = 0
productions.each do |p|
total += p.quantity if p.start_time and p.finish_time
end
total
end
def number_of_dispatched_items
total = 0
dispatches.each do |p|
total += p.quantity
end
total
end
def number_of_items_in_progress
total = 0
productions.each do |p|
total += p.quantity if not p.finish_time
end
total
end
def enough_items_to_be_dispatched?
if (number_of_produced_items > 0 and number_of_dispatched_items <
number_of_produced_items) then true else false end
end
,and don't want to redefine them in every find method, it takes a lot
of time
for ex., one of these fields I redefined for one of the combo boxes as
quite long SQL:
select("dispatch", "order_id",
Order.find_by_sql("SELECT * FROM orders o WHERE id in
(
SELECT p.order_id FROM productions p
WHERE p.start_time is not NULL and p.finish_time is not NULL
GROUP BY p.order_id
HAVING sum(p.quantity) > IFNULL(
(
SELECT sum(d.quantity) FROM dispatches d
WHERE d.order_id = p.order_id
GROUP BY d.order_id
) ,0)
)
I think in certain cases it’s absolutely kosher to just add methods like you did. Just make sure it doesn’t create additional SQL select calls for you, for example, use :include => :productions when calling find for your model.
It depends on the size of the related record set (productions). Looping through a huge recordset will probably be less performant (and more cpu and memory intensive) than using SQL to get what you want. However, don’t look for problems and bottlenecks as long as they’re not there. Switching these methods in your model to an SQL query instead of what you have now should be a trivial task, so if there’s ever a need to increase performance, it will be the time to look at other options such as an SQL query. For now, this is probably just fine.
Looks like :find only constructs SQL. I'm wondering is It possible to
rewrite some of fields in my model using SQL, e.g.
"number_of_items_in_progress" and then use them in :find?