LoginSignup
1
3

More than 5 years have passed since last update.

【検討中】railsで関連付けさせた中間テーブルに値を入れたい(できれば一括で)

Posted at

目的

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の場合、新しく作ってほしくないのでこれはダメ。

検討中

tagに重複させる形でsaveできないか

form通りに値を渡す

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3