Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 当某个标记不再在任何post中使用时,从Rails数据库中删除标记元素_Ruby On Rails - Fatal编程技术网

Ruby on rails 当某个标记不再在任何post中使用时,从Rails数据库中删除标记元素

Ruby on rails 当某个标记不再在任何post中使用时,从Rails数据库中删除标记元素,ruby-on-rails,Ruby On Rails,我正在编写一个简单的博客风格的Rails应用程序,并成功地添加了一个相当简单的#标记功能。我面临的问题是,我想不出一种方法来删除任何帖子中不再使用的标签。例如,如果我在第一篇文章中创建了一个标记#twitter,然后删除该文章,那么标记#twitter将保留在我的数据库中,即使它没有在任何地方使用/引用。我想删除未使用的标签。为关系创建第三个DB表(post有许多标记,标记属于许多post),标记和post之间的关系是“has_和_属于_-many” 我创建标记的一种方法是创建标记模型和表,然后

我正在编写一个简单的博客风格的Rails应用程序,并成功地添加了一个相当简单的#标记功能。我面临的问题是,我想不出一种方法来删除任何帖子中不再使用的标签。例如,如果我在第一篇文章中创建了一个标记#twitter,然后删除该文章,那么标记#twitter将保留在我的数据库中,即使它没有在任何地方使用/引用。我想删除未使用的标签。为关系创建第三个DB表(post有许多标记,标记属于许多post),标记和post之间的关系是“has_和_属于_-many”


我创建标记的一种方法是创建
标记
模型和表,然后创建
标记
模型和表

tag.rb

class Tag < ApplicationRecord

  has_many :taggings
  has_many :posts, through: :taggings

end
class标记
tagging.rb

class Tagging < ApplicationRecord
  belongs_to :tag
  belongs_to :post
end
类标记
post.rb

class Post < ApplicationRecord
  has_many :taggings
  has_many :tags, through: :taggings
end
class Post

现在您只需要使用post_id和tag_id连接这两个元素的连接表。这样,您可以在标记表上强制执行
uniq
,以避免冗余标记。如上所述,您可以构建一个
after_destroy
方法,在检查标记是否在其他地方使用后删除该标记。或者像Dave Newton提到的那样,为了自动完成建议,将其保留在历史上。

检查已删除帖子中的任何标签是否不再有引用,如果没有,则删除。这不是一次非常有用的行动,国际海事组织;通常,您希望尝试规范化和建议标记,这意味着您希望您的标记历史语料库仍然可用。
**schema.rb**
  create_table "posts", force: :cascade do |t|
    t.string "title"
    t.text "body"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer "user_id"
    t.string "image_filename"
    t.string "posts"
    t.string "image"
  end

  create_table "posts_tags", id: false, force: :cascade do |t|
    t.bigint "post_id"
    t.bigint "tag_id"
    t.index ["post_id"], name: "index_posts_tags_on_post_id"
    t.index ["tag_id"], name: "index_posts_tags_on_tag_id"
  end

  create_table "tags", force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end
class Tag < ApplicationRecord

  has_many :taggings
  has_many :posts, through: :taggings

end
class Tagging < ApplicationRecord
  belongs_to :tag
  belongs_to :post
end
class Post < ApplicationRecord
  has_many :taggings
  has_many :tags, through: :taggings
end