Reputation: 5953
When my app creates a new work order, it also creates the first task associated with that work order. The new task should have it's taskstatus set to the very first id in the Taskstatus table.
The first record in the Taskstatus table happens to have an id = 2.
But, the code sets the task.taskstatus_id = 1
Workorder Controller code:
before_create :first_task
protected
def first_task
self.tasks.build taskstatus_id: Taskstatus.first, taskname: self.description
end
What am I missing? Thanks!
UPDATE ---- The first record in the taskstatus table has id = 2. The record with id = 1 was deleted. I want the new task record to have a taskstatus_id = 2.
In the taskstatus.rb, I have:
default_scope :order => 'id ASC'
This also created a task with taskstatus = 1
Taskstatus.limit(1)
I'm using postgreSQL.
On the taskstatus index page, 3 records display =
id statuscode
2 New
3 Started
4 Completed
Something weird is happening!!
UPDATE 2 - You aren't going to believe this !!!!!! (I wouldn't) - but, it's true.
I changed the code to this:
Taskstatus.where(:statuscode => "New")
And even though New has id = 2, the task got 1
Could something be wrong with postgreSQL?
Upvotes: 0
Views: 132
Reputation: 239291
As other have said,.first
is un-ordered.
You can solve this by adding an explicit ordering (.order(:id).first
), or by using a default_scope
to always order the results:
class Taskstatus < ActiveRecord::Base
default_scope order(:id)
end
Now Taskstatus.first
will always be the first record, ordered by id. This may be useful if your ordering changes, and you wind up considering with one with the earliest created_at
to be the "first" record.
Upvotes: 1