Ruby on rails - 从数组创建多个记录

时间:2016-12-20 17:38:33

标签: ruby-on-rails arrays database activerecord

我的模型grep有一个表单。我尝试使用除@gig之外的相同属性一次创建多个gigs,这些属性应从数组中选取。

到目前为止,只有数组中的最后一个日期才会保存一条记录。

_form.html.erb

date

gig_controler.rb

    <%= simple_form_for @gig , url: gigs_path do |form| %>
         <div class="create-title">
            <%= form.input :title, label: t('gig.title'), placeholder: t('placeholder.title') %>
         </div>

          bla... bla... bla....

         <p><%= t('gig.date') %> </p>
           <% if !mobile_device? %>
             <%= form.input :date, as: :string, label: false, placeholder: t('placeholder.date'), multiple: true %>
           <% else %>

                       bla... bla... bla....
    <% end %>

在控制器中使用 def create @gigdates = params[:gig][:date].split(';') puts @gigdates.count @gigdates.each do |date| puts date @gig = Gig.create(gig_params) @gig.date = date end if @gig.save redirect_to @gig else Rails.logger.info(@gig.errors.inspect) render 'new' end end def gig_params params.require(:gig).permit(:title, :location, :description, :date, :salary, :salary_cents, :salary_currency, :genre_ids => []) end ,我可以看到我的日期正确分开。

服务器显示puts date被调用的次数与数组中的日期一样多,然后最终ROLLBACK正确保存。

更新1:

我已经更改了允许创建多个记录的控制器,我只是担心如果记录无法保存,则缺少重定向或消息。

gig

1 个答案:

答案 0 :(得分:1)

对于@gig_dates数组中的每个日期,您正在使用gig_params创建无效的演出。它无效,因为date的{​​{1}}键将是最初在表单中输入的字符串,例如gig_params。这是一个无效的日期,因此所有"2017-01-3;2017-05-09;2017-08-01" - 您对ROLLBACK的调用都在数据库级别失败。

让我们深入了解正在发生的事情:

Gig.create

编辑:

处理验证的一种方法是在保存任何新演出之前检查所有新演出的有效性。要执行此操作,您可以使用地图替换 # EACH LOOP BEGINS # for each gig date: @gigdates.each do |date| # gig_params[:date] will be the whole string that was entered in the # form. this is an invalid date, so Gig.create will fail to save the # gig to the database (= ROLLBACK). # so you create an gig, but it can't be saved because its date parameter # is invalid. you assign this invalid gig to the @gig instance # variable. this variable will be overwritten each time, so only the # last created gig is stored in @gig @gig = Gig.create(gig_params) # you assign that invalid gig a (valid) date (but you don't save it!) @gig.date = date end # EACH LOOP ENDS # Save @gig, the last created gig, using the valid date you assigned # it at the end of the each loop. so now the save will work! if @gig.save redirect_to @gig else Rails.logger.info(@gig.errors.inspect) render 'new' end end ,这将创建新演出阵列,然后在全部保存之前检查它们是否都有效:

each