1
votes

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.

2
Side note...When you run a query and you are expecting a single record you can call .first on the relation to grab it. @Marek's answer is what you are looking for here.Mark Merritt

2 Answers

4
votes

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
1
votes

if you want to remove column, you can use

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