Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/52.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 rails有很多更新创建,并且属于_Ruby On Rails_Has And Belongs To Many - Fatal编程技术网

Ruby on rails rails有很多更新创建,并且属于

Ruby on rails rails有很多更新创建,并且属于,ruby-on-rails,has-and-belongs-to-many,Ruby On Rails,Has And Belongs To Many,我有两种型号: class Topic < ActiveRecord::Base has_and_belongs_to_many :tags end class Tag < ActiveRecord::Base has_and_belongs_to_many :topics end 类主题

我有两种型号:

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
class表单::NewTopic
包括ActiveModel::Model
属性访问器:标题,:用户id,:原始链接,:描述,:标记
def保存
主题标签=[]
@tags.gsub(/\s+/m',).strip.split(“”).uniq.each do|tag|u name|
tag=tag.find_或_create_by name:tag_name

您想要更新的主题标记意味着。?并且我们不应该创建单独的模型来创建关联。我们肯定可以改进这一点,我会告诉你为什么你要在模型中进行创作。这可以在控制器中完成,其余的逻辑可以移动到助手