0

I have on my controller something like

@account = @user.accounts.first

where I only want to display the first item in the accounts array. But whenever I add a new account, @account now refers to the last item in the accounts array.

Locally, with SQLite3, it works correctly, @account always refers to the first item in the accounts array, but on heroku with postgresql, is when that happens.

Why this is happening?

tvieira
  • 1,775
  • 3
  • 25
  • 44

2 Answers2

1

According to this issue in the rails repository, you should explicitly state the ordering to ensure this works correctly:

@account = @user.accounts.order(:created_at).first
benjaminjosephw
  • 4,269
  • 3
  • 19
  • 39
0

Postgres tables do not have an implicit order. If you want a guaranteed order, you need to add .order to your query:

@account = @user.accounts.order(id: :asc).first

would give you the first account created for this user,

@account = @user.accounts.order(id: :desc).first

the last.

janfoeh
  • 10,235
  • 2
  • 30
  • 55