如何创建多个新记录,检查现有重复项以及添加新记录或现有记录以加入表

时间:2017-05-24 16:55:46

标签: ruby-on-rails

我正在撰写一个简单的博客应用,可以通过

创建帖子并为帖子添加多个标签

has_many :tags, :through => :tag_joins

标签是从输入到视图中的逗号分隔字符串中提取的,该视图在后期创建操作中由正则表达式分隔为单个标记。

def create
@post = Post.new(post_params)
respond_to do |format|
  if @post.save
    @tags = @post.tagstring.split(/\s*,\s*/)
    @tags.each do |i|
      @tag = Tag.new(:name => i)
      if @tag.save
        @post.tags << @tag
      end
    end
    format.html { redirect_to "/#{@post.permalink}", notice: "success" }
  else
    format.html { render action: 'new' }
  end
end
end

除了在标记表中创建重复的标记外,这种方法很好。

我如何检查标签是否已经存在,如果已存在,则将现有标签添加到帖子而不是创建新标签?我已经看过使用first_or_create,但我很难理解它是如何适应另一个创建动作的上下文。

2 个答案:

答案 0 :(得分:1)

使用find_or_initialize_by。像这样:

  @tag = Tag.find_or_initialize_by(:name => i)

因为,如果@tag已经存在,那么您将无法创建新的。{/ p>

然后你可能想对它进行一些检查,例如:

  if @tag.new_record? 
    @post.tags << @tag if @tag.save
  else
    @post.tags << @tag
  end

if声明有点像jenk。对于那个很抱歉。如果我是你,我会花几分钟让它变冷。

答案 1 :(得分:1)

是的,first_or_initialize会帮助你..

@tags.each do |i|
  tag = Tag.where(name: i).first_or_initialize
  if tag.persisted? || tag.save
    @post.tags << tag
  end
end

在此处查看文档persisted?

如果有可能删除标签,请检查!tag.new_record?

阅读new_record?

相关问题