For some reason, the order method is not working in my code. If I do in a model:
def apple
@tasks_array = self.tasks.to_a
end
With the code above, an array is returned. But if I do:
def apple
@tasks_array = self.tasks.order('order_number').to_a
end
then
[]
is returned. Here is the array that should be returned and that gets returned with the first block of code I wrote:
[#<Task id: 145, title: "task 1", content: "", created_at: "2013-12-18 18:44:31",
updated_at: "2013-12-18 20:21:11", schedule_id: 79, amount: nil,
time_frame: "2013-12-19 15:00:00", state: "complete", denied: 3,
order_number: 0>, #<Task id: 146, title: "Task 2", content: "",
created_at: "2013-12-18 18:44:31", updated_at: "2013-12-18 20:24:06",
schedule_id: 79, amount: nil, time_frame: "2013-12-27 10:00:00",
state: "complete", denied: 1, order_number: 1>]
I have also tried taking out .to_a but it still does not work.
The only explanation I can think of for this behavior is that:
self
has yet to be saved, orbut the value of tasks
remains cached. order
involves a SQL query, so it requires that the database be accessed.
The evidence for this would be that you see a SQL query echoed to the console only for the case of order
being used.
As an alternative, you case use Enumerable#sort_by
as follows:
self.tasks.sort_by {|task| task.order_id}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With