简体   繁体   English

Ruby on Rails:我可以使用ID以外的属性/列删除记录吗?

[英]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. 我需要在Heroku rails控制台中删除一些博客帖子,而我没有足够的经验来解决这个问题。

I can see the blog post slug in the url, could I delete the blog posts utilizing its slug? 我可以在网址中看到博客帖子slug,我可以使用它的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? 我也知道那些特定博客所属的topic_id会帮助我识别和删除这些博客帖子吗?

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 . 通过执行步骤1: Topic.find(18) ,步骤2: topic = Topic.find(18)和步骤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: 使用slug:

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

Using topic_id 使用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. 通过slug博客我认为比topic_id更好的方法,因为主题可能有更多的博客,你可能不想删除它。

  • In any case, review the blogs before deleting as it is irreversible. 在任何情况下,请在删除之前查看博客,因为它是不可逆转的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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