简体   繁体   中英

How to destroy/delete a Rails Active Record without an id column?

Is there a way to destroy Rails Active Record entries in a table without an id column? I know there are a few ways to destroy Active Records with ids , like these:

User.destroy(1)
User.first.destroy

However, I cannot seem to find a way to do so without an id . I've checked the suggestions in this link but to no avail. Ideally, what I have in mind is something like this:

User.where(name: "Dummy").destroy
# Returns this:
# ArgumentError (wrong number of arguments (given 0, expected 1))

I know that it's generally discouraged to create tables in Rails without an id column. While I'd like to rid of it for this particular table if possible, I am willing to make the column if it turns out there are no workarounds. Thanks in advance.

The reason User.where(name: 'Dummy').destroy doesn't work is User.where(name: 'Dummy') is a relation, not a single record. If you want, for example, to destroy all the records with name equal to 'Dummy' , you can use destroy_all :

User.where(name: 'Dummy').destroy_all

if you want to remove column, you can use

User.find_by_name(name: "dummy").destroy

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