我有两个模型:
class Topic < ActiveRecord::Base
has_and_belongs_to_many :tags
end
class Tag < ActiveRecord::Base
has_and_belongs_to_many :topics
end
我制作了一个模型来创建它们。
class Forms::NewTopic
include ActiveModel::Model
attr_accessor :title, :user_id, :raw_link, :description, :tags
def save
topic_tags = []
@tags.gsub(/\s+/m, ' ').strip.split(" ").uniq.each do |tag_name|
tag = Tag.find_or_create_by name: tag_name
topic_tags << tag if tag.errors.blank?
break if topic_tags.count == 3
end
Topic.create title: @title,
user_id: @user_id,
raw_link: @raw_link,
description: @description,
tags: topic_tags
end
end
但是当我想更新它们时,我找不到更好的解决方案。
有没有更好的方案来解决场景?谢谢 :)