简体   繁体   中英

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

I am trying to use the standard create method created for Ruby/Rails projects and simply pass in an additional form field that tells the method how many objects to create (vs just creating one object). The standard create method looks like so:

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

I want to pass in an additional data (form field called number_to_create) which tells the method how many of the microposts to create. I just added a new form field like this, in addition to the other micropost form field params:

<%= text_field_tag :number_to_create %>

My question is how do I modify the create method code such that it creates N number of micropost objects vs. just one. So if I pass in 3 from the form along with the other micropost attributes, the method creates 3 identical micropost objects, not just one as it currently does.

Thanks in advance for your help on this.

You could use the param as times

@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

The transaction block is to make sure that either all of them gets saved, or none of them gets saved, this way you can fix your errors and recreate them without worrying of getting any stray saved objects

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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