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,865
  • 3
  • 28
  • 45

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,369
  • 3
  • 21
  • 40
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,243
  • 2
  • 31
  • 56