Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/62.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 如何创建多个新记录、检查现有重复项以及将新记录或现有记录添加到联接表_Ruby On Rails - Fatal编程技术网

Ruby on rails 如何创建多个新记录、检查现有重复项以及将新记录或现有记录添加到联接表

Ruby on rails 如何创建多个新记录、检查现有重复项以及将新记录或现有记录添加到联接表,ruby-on-rails,Ruby On Rails,我正在编写一个简单的博客应用程序,它通过 有许多:标记,:通过=>:tag\u连接 标记是从输入视图的逗号分隔字符串中提取的,该字符串由post create操作中的正则表达式分隔为单个标记 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\u连接

标记是从输入视图的逗号分隔字符串中提取的,该字符串由post create操作中的正则表达式分隔为单个标记

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
def创建
@post=post.new(post_参数)
回应待办事项|格式|
如果@post.save
@tags=@post.tagstring.split(/\s*,\s*/)
@标签。每个都有| i|
@tag=tag.new(:name=>i)
如果@tag.save

@post.tags使用
find\u或\u initialize\u by
。大概是这样的:

  @tag = Tag.find_or_initialize_by(:name => i)
因为,如果
@tag
已经存在,则不会创建新的标签

然后你可能想做一些检查,比如:

  if @tag.new_record? 
    @post.tags << @tag if @tag.save
  else
    @post.tags << @tag
  end
if@tag.new\u记录?

@post.tags使用
find\u或\u initialize\u by
。大概是这样的:

  @tag = Tag.find_or_initialize_by(:name => i)
因为,如果
@tag
已经存在,则不会创建新的标签

然后你可能想做一些检查,比如:

  if @tag.new_record? 
    @post.tags << @tag if @tag.save
  else
    @post.tags << @tag
  end
if@tag.new\u记录?

@post.tagsYes,
first\u或\u initialize
将帮助您

@tags.each do |i|
  tag = Tag.where(name: i).first_or_initialize
  if tag.persisted? || tag.save
    @post.tags << tag
  end
end
@tags.each do|i|
tag=tag.where(名称:i).首先\u或\u初始化
如果tag.persistent?||tag.save

@post.tagsYes,
first\u或\u initialize
将帮助您

@tags.each do |i|
  tag = Tag.where(name: i).first_or_initialize
  if tag.persisted? || tag.save
    @post.tags << tag
  end
end
@tags.each do|i|
tag=tag.where(名称:i).首先\u或\u初始化
如果tag.persistent?||tag.save

@post.tags工作得很好,谢谢。我不知道
持续存在?
。。我有点学习如何好好工作,谢谢。我不知道
持续存在?
。。我也在学习如何做好这件事,谢谢。我同意了另一个答案,因为他帮我拿了一个更酷的if语句,但打得很好!他的
if
声明肯定更好!这也很有效,谢谢。我同意了另一个答案,因为他帮我拿了一个更酷的if语句,但打得很好!他的
if
声明肯定更好!