简体   繁体   中英

Does Rails Auto-Assign ID's?

I'm trying to sort my users in my controller, and I wanted to sort them by id number. My question is, does rails automatically assign orders an id when they are created, or do I need to add that to the create function in my create action in my controller? For example, can I say this:

def index
  @users = User.all.order(:WHAT TO PUT HERE???????)
end

Would I put :id in the space? If I did so, would I need to define id somewhere else or is this something ruby does on the back end?

In most cases Rails would return you records sorted by id. But you should not rely on Rails as sorting is database-specific.

To explicitly add sorting by id you should use:

def index
  @users = User.order(:id)
end

Id is automatically added, you don't need to declare it anywhere.

Rails only helps you create the table via migrations. When a migration creates a table it automatically adds the id column as a primary key set to auto increment. So why you create records it's actually the database that adds the id, or as aforementioned, it auto increments it +1 from the last id. Therefore, when you use ActiveRecord to create a record you don't need to specify an id.

Now for your main question: you can pass the name of the column to the order method when you want to sort ascending by that column. You don't need to call all though.

So just do this:

User.order(:id)

That will sort from lower ids to higher. To do the opposite:

User.order("id DESC")

This will give your the most recently created records first by sorting from higher ids to lower.

If you want to sort User by ID

 @users = User.order(:id)  #ASC default

 @users = User.order('id ASC')  #ASC explicit

 @users = User.order('id DESC')  #DESC explicit

...永远不要忘记User.order('-id')一元减快捷方式...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM