目的
railsで下記の形でtag_mapのmodelを作り、tag_mapに一括でインポートしたい。(現在模索中)
model
post.rb
class Post < ApplicationRecord
has_many :tag_maps, dependent: :destroy, foreign_key: 'post_id'
has_many :tags, through: :tag_maps
def save_posts(savepost_tags)
current_tags = self.tags.pluck(:name) unless self.tags.nil?
old_tags = current_tags - savepost_tags
new_tags = savepost_tags - current_tags
# Destroy old taggings:
old_tags.each do |old_name|
self.tags.delete Tag.find_by(name:old_name)
end
# Create new taggings:
new_tags.each do |new_name|
post_tag = Tag.find_or_create_by(name:new_name)
self.tags << post_tag
end
end
end
tag.rb
class Tag < ApplicationRecord
validates :name,presence:true,length:{maximum:50}
has_many :tag_maps, dependent: :destroy, foreign_key: 'tag_id'
has_many :posts, through: :tag_maps
end
tag_map.rb
class TagMap < ApplicationRecord
belongs_to :post
belongs_to :tag
validates :post_id,presence:true
validates :tag_id,presence:true
end
ダメだった方法
直接入力
tag_mapのdbに直接書き込むはtag_mapのpkが重複してしまうのでダメだった。actionrecordがおそらくthroughして向こう側で生成しないとpkを発行しないんだと思う。
rails cでtagをcreate
tagをcreateすると重複しているのにもかかわらず違うレコードを作ってしまう。今回同じtagの場合、新しく作ってほしくないのでこれはダメ。