#64 バックエンドぼちぼち
This commit is contained in:
@@ -78,6 +78,7 @@ class PostsController < ApplicationController
|
||||
if post.save
|
||||
post.resized_thumbnail!
|
||||
post.tags = Tag.normalise_tags(tag_names)
|
||||
post.tags = Tag.expand_parent_tags(post.tags)
|
||||
render json: post.as_json(include: { tags: { only: [:id, :name, :category, :post_count] } }),
|
||||
status: :created
|
||||
else
|
||||
@@ -111,6 +112,7 @@ class PostsController < ApplicationController
|
||||
|
||||
post = Post.find(params[:id].to_i)
|
||||
tags = post.tags.where(category: 'nico').to_a + Tag.normalise_tags(tag_names)
|
||||
tags = Tag.expand_parent_tags(tags)
|
||||
if post.update(title:, tags:, original_created_from:, original_created_before:)
|
||||
render json: post.as_json(include: { tags: { only: [:id, :name, :category, :post_count] } }),
|
||||
status: :ok
|
||||
|
||||
@@ -11,6 +11,14 @@ class Tag < ApplicationRecord
|
||||
dependent: :destroy
|
||||
has_many :linked_nico_tags, through: :reversed_nico_tag_relations, source: :nico_tag
|
||||
|
||||
has_many :tag_implications, foreign_key: :parent_tag_id, dependent: :destroy
|
||||
has_many :children, through: :tag_implications, source: :tag
|
||||
|
||||
has_many :reversed_tag_implications, class_name: 'TagImplication',
|
||||
foreign_key: :tag_id,
|
||||
dependent: :destroy
|
||||
has_many :parents, through: :reversed_tag_implications, source: :parent_tag
|
||||
|
||||
enum :category, { deerjikist: 'deerjikist',
|
||||
meme: 'meme',
|
||||
character: 'character',
|
||||
@@ -61,6 +69,29 @@ class Tag < ApplicationRecord
|
||||
tags.uniq
|
||||
end
|
||||
|
||||
def self.expand_parent_tags tags
|
||||
return [] if tags.blank?
|
||||
|
||||
seen = Set.new
|
||||
result = []
|
||||
stack = tags.compact.dup
|
||||
|
||||
until stack.empty?
|
||||
tag = stack.pop
|
||||
next unless tag
|
||||
|
||||
tag.parents.each do |parent|
|
||||
next if seen.include?(parent.id)
|
||||
|
||||
seen << parent.id
|
||||
result << parent
|
||||
stack << parent
|
||||
end
|
||||
end
|
||||
|
||||
(result + tags).uniq { |t| t.id }
|
||||
end
|
||||
|
||||
private
|
||||
|
||||
def nico_tag_name_must_start_with_nico
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
class TagImplication < ApplicationRecord
|
||||
belongs_to :tag, class_name: 'Tag'
|
||||
belongs_to :parent_tag, class_name: 'Tag'
|
||||
|
||||
validates :tag_id, presence: true
|
||||
validates :parent_tag_id, presence: true
|
||||
|
||||
validate :parent_tag_mustnt_be_itself
|
||||
|
||||
private
|
||||
|
||||
def parent_tag_mustnt_be_itself
|
||||
if parent_tag == tag
|
||||
errors.add :parent_tag_id, '親タグは子タグと同一であってはなりません.'
|
||||
end
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user