在Rails中使用循环创建多个记录

时间:2016-08-21 21:34:51

标签: ruby-on-rails ruby model-view-controller

我有一个Shift类和一个表单来创建一个新的班次。我希望能够一次创建多个班次,背靠背,这样我只需要选择日期和开始时间以及应该创建多少班次。班次是30分钟。

我现在有一个自定义控制器方法,它在由用户选择的param:block确定的循环中调用create方法。我现在已经停止收到错误消息了,但是当我提交表单时,我不知道会发生什么,这似乎没什么。我的问题是:我如何修改我的create_block方法,以便它能满足我的需求?

Shifts_controller:

  def create
    @shift = Shift.new(shift_params)
    if @shift.save
      #redirect_to shifts_url
    else
      render 'new'
    end
  end

  def create_block
    start = params[:start_time]
    stop = params[:start_time] + 30.minutes
    block = params[:block]
    for number in 1..block do
      Shift.create(date:params[:date], start_time:start, stop_time:stop)
      start = stop
      stop = stop + 30.minutes
    end
    redirect_to shifts_url
  end

_form.html.erb

<%= form_for @shift, :url => create_block_path(@shift) do |f| %>
<%= render 'shared/error_messages', object: f.object %>


<div class="field">
    <%= f.label :Datum %>
    <%= f.date_select :date %>
  </div>
  <br>
  <div class="field">
    <%= f.label :Börjar %>
    <%= f.time_select :start_time, {minute_step: 30} %>
  </div>
  <br>
  <div>
    <%= f.label :Antal %>
    <%= f.select :block, options_for_select(1..10) %>
  </div>
  <br>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

的routes.rb

resources :shifts do
  member do
    patch 'book/' => 'shifts#book', as: 'book'
    patch 'un_book/' => 'shifts#un_book', as: 'un_book'
  end
end
get 'shifts/:id/book' => 'shifts#book'
get 'shifts/:id/un_book' => 'shifts#un_book'
match '/shifts/new' => 'shifts#new', as: 'create_block', via: [:post]

1 个答案:

答案 0 :(得分:1)

您的路由正在将create_block操作路由到ShiftsController#new。您需要将其路由到ShiftsController#create_block

尝试:

resources :shifts do
  member do
    patch 'book/' => 'shifts#book', as: 'book'
    patch 'un_book/' => 'shifts#un_book', as: 'un_book'
  end
  collection do
    post 'create_block' => 'shifts#create_block', as: 'create_block'
  end
end
get 'shifts/:id/book' => 'shifts#book'
get 'shifts/:id/un_book' => 'shifts#un_book'