【问题标题】:Create more than one object at once using the standard create method in Ruby on Rails使用 Ruby on Rails 中的标准 create 方法一次创建多个对象
【发布时间】:2015-02-26 14:35:46
【问题描述】:

我正在尝试使用为 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 的表单字段),它告诉方法要创建多少微博。我刚刚添加了一个这样的新表单字段,除了其他微帖子表单字段参数:

<%= text_field_tag :number_to_create %>

我的问题是如何修改 create 方法代码,使其创建 N 个 micropost 对象而不是一个。因此,如果我从表单中传入 3 以及其他 micropost 属性,则该方法会创建 3 个相同的 micropost 对象,而不是像现在这样。

在此先感谢您的帮助。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4


    【解决方案1】:

    你可以使用参数作为时间

    @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
    

    事务块是为了确保它们都被保存,或者它们都不被保存,这样你就可以修复错误并重新创建它们,而不必担心得到任何杂散的保存对象

    【讨论】:

    • 喜欢这种方法,tx!但是在所有微博创建(或失败)之后,您将如何处理 respond_to 方法和 redirect 方法?您提到将其包装在事务中,但我不熟悉 Ruby 中的事务。您能否为我提供一个使用您已经开始的解决方案的示例?发送!
    • 是的,if 和 else 组件。
    • 太棒了!!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    • 2018-11-16
    相关资源
    最近更新 更多