简体   繁体   中英

Ruby on Rails: Can I delete records using attributes/columns other than ID?

I need to delete a couple of blog posts in Heroku rails console and I don't have enough experience of how to go about it.

I can see the blog post slug in the url, could I delete the blog posts utilizing its slug? If so, how?

This is what my schema looks like for those blogs:

 create_table "blogs", force: :cascade do |t|
    t.string "title"
    t.text "body"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "slug"
    t.integer "status", default: 0
    t.bigint "topic_id"
    t.index ["slug"], name: "index_blogs_on_slug", unique: true
    t.index ["topic_id"], name: "index_blogs_on_topic_id"
  end

I also know the topic_id which those particular blogs belong to, would that help me identify and delete those blog posts?

I was able to identify the blogs in a topic by doing Step 1: Topic.find(18) , Step 2: topic = Topic.find(18) and Step 3: topic.blogs.first . Is there a way I can delete that first topic?

You can use both to refer to those blogs:

Using slug:

list = ['slug1', 'slug2',..]
blogs = Blog.where(slug: list)
blogs.destroy_all

Using topic_id

list = ['topic1', 'topic2',..]
blogs = Blog.where(topic_id: list)
blogs.destroy_all

Caution

  • Blogs through slug is I believe good approach than topic_id because topics may have more blogs which you might not want to delete it.

  • In any case, review the blogs before deleting as it is irreversible.

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