Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails .order method not working

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.

like image 495
Philip7899 Avatar asked Nov 23 '22 07:11

Philip7899


1 Answers

The only explanation I can think of for this behavior is that:

  • self has yet to be saved, or
  • the task records do not exist in the database at the time this statement is executed
  • the task records are no longer associated with self

but 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}
like image 191
Peter Alfvin Avatar answered Nov 25 '22 20:11

Peter Alfvin