繁体   English   中英

使用Ruby on Rails中的标准创建方法一次创建多个对象

[英]Create more than one object at once using the standard create method in Ruby on Rails

我试图使用为Ruby / Rails项目创建的标准create方法,并简单地传递一个附加的表单字段,该字段告诉该方法要创建多少个对象(相对于仅创建一个对象)。 标准的创建方法如下所示:

def create
@micropost = Micropost.new(micropost_params)

respond_to do |format|
  if @micropost.save
    format.html { redirect_to @micropost, notice: 'Micropost was successfully created.' }
    format.json { render :show, status: :created, location: @micropost }
  else
    format.html { render :new }
    format.json { render json: @micropost.errors, status: :unprocessable_entity }
  end
end
end

我想传递一个附加数据(称为number_to_create的表单字段),该数据告诉方法要创建多少个微职位。 除了其他micropost表单字段参数外,我只是添加了一个这样的新表单字段:

<%= text_field_tag :number_to_create %>

我的问题是如何修改创建方法代码,以使其创建N个微博对象,而不是一个。 因此,如果我从表单中传入3以及其他微博属性,则该方法会创建3个相同的微博对象,而不仅仅是当前的对象。

在此先感谢您的帮助。

您可以将参数用作时间

@microposts = Micropost.transaction do 
  [].tap do |microposts|
    param[:number_to_create].times do
      microposts << Micropost.create(micropost_params)
    end
  end
end

respond_to do |format|
  if @microposts.all? &:persisted?
    format.html { redirect_to @micropost, notice: 'Micropost was successfully created.' }
    format.json { render :show, status: :created, location: @micropost }
  else
    format.html { render :new }
    format.json { render json: @micropost.errors, status: :unprocessable_entity }
  end
end

事务块是确保要么全部保存,要么全部都不保存,这样您就可以修复错误并重新创建它们,而不必担心会得到任何散乱保存的对象

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM