在一个表单轨道中创建多个对象

时间:2018-08-01 09:44:38

标签: ruby-on-rails forms ruby-on-rails-5 cocoon-gem

我要达到的目标是一个看起来像嵌套形式的网页(因此能够添加新元素并删除已经存在的元素)。这里的问题是它不是嵌套表单,而是只有一个模型。

class MyModel < ApplicationRecord
end

我想创建和编辑/创建/更新页面(全部集成)...我的控制器现在看起来像这样

def configure
  @config_items = MyModel.all
end

这是渲染页面

def config_update
  @config_items = MyModel.all
  errors = save_configs
  respond_to do |format|
    if errors.empty?
      flash[:success] = "message"
      format.html { redirect_to root_path}
      format.json { render json: @config_items, status: :ok }
    else
      flash.now[:danger] = "message"
      format.html { render :configure }
      format.json { render json: ?what?, status: :unprocessable_entity }
    end
  end
end

这是更新操作

def save_configs
   @config_items = []
   errors = []
   params[:config_items].each do |id, name|
     item = MyModel.find_or_create_by(id: id)
     errors << item.errors unless item.update_attributes(name: name[:name])
     @config_items << item
   end
   errors
 end
def config_params
  params.require(:config_items).permit(:id,
                                       :name
                                      )
end

及其方法

<%= form_with url: update_configs_members_path do |form| %>
    <%= hidden_field_tag 'type', params[:type] %>
    <div id="items" class="col-md-12 p-0 pl-md-3">
      <% @config_items.each do |config| %>
        <%= form.fields_for "config_items[]", config do |configForm| %>
          <%= render 'config_fields', f: configForm %>
        <% end %>
      <% end %>
    </div>
    <%= submit_tag 'Update Configurations', class: 'btn btn-warning btn-block my-2' %>
  <% end %>

这是我当前的视图(配置视图)

<div class="nested-fields">
  <div class="field form-group row">
    <%= f.label :name, 'Name:', class: 'col-sm-1 col-form-label' %>
    <div class="col-sm-10">
      <%= f.text_field :name, class: 'form-control ml-2' %>
    </div>
    <div class="col-sm-1 p-0">
      <%= link_to "&times;".html_safe, ?destroy_field?, class: 'badge badge-pill badge-danger mt-2' %>
    </div>
  </div>
</div>

和部分

在当前阶段,我可以轻松地更新模型的每个实例,但是我想要的是一种销毁和创建新记录的方法。所以问题是我该怎么做? (如果可能的话,我想使用茧宝石)

0 个答案:

没有答案