使用Cocoon gem

时间:2017-01-23 23:16:20

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

我有一个模型的应用程序,我们称之为Box,Stock,Experiment,&样品。以下是ActiveRecord关系的样子:

class Box
  has_many :stocks
  accepts_nested_attributes_for :stocks
end

class Stock
  belongs_to :box
  has_many :samples
end

class Experiment
  has_many :samples
  accepts_nested_attributes_for :samples
end

class Sample
  belongs_to :experiment
  belongs_to :stock
end

我想在我的Box#show页面上有一个按钮,名为" Gene From Experiment From Box。"理想情况下,这将带我进入我的实验#新页面,其中包含样本的预先填充的嵌套字段 - 每个库存一个样本。 样品还不应该是保存对象,因为我希望用户能够在保存实验之前修改样品。但是,我目前无法将嵌套字段预填充。

应用程序/视图/盒/ show.html.erb

<%= link_to 'Generate New Experiment Box', new_experiment_path(box_id: @box.id) %>

应用程序/控制器/实验/ experiments_controller.rb

def new
  if params[:box_id]
    stocks = Box.find(params[:box_id]).stocks
    samples_attributes = stocks.map { |stock| { stock_id: stock.id } }
    @experiment = Experiment.new(samples_attributes: samples_attributes)
  else
    @experiment = Experiment.new
  end
end

应用程序/视图/实验/ new.html.erb

<%= simple_form_for(@experiment) do |f| %>
  <div>
    #various form inputs
  </div>

  <div>
    <table>
      <thead>#column headers</thead>
      <tbody id="samples-table">
        <%= f.simple_fields_for :samples, f.object.samples.order(:id) do |sample_fields| %>
          <%= render 'sample_fields', f: sample_fields %>
        <% end %>        
      </tbody>
    </table>
    <div id="Links">
      <%= link_to_add_association "Add Samples to Experiment", f, :samples, :"data-association-insertion-node" => 'tbody#samples-table', :"data-association-insertion-method" => 'append' %>        
    </div>
  </div>
<% end %>

应用程序/视图/实验/ _sample_fields.html.erb

<tr class="nested-fields form-inline form-table-row">
  <td>#various text fields</td>
  <td>#various text fields</td>
</tr>

非常感谢任何帮助!我已经尝试了一些不同的方法解决这个问题,但仍然无法填充嵌套字段。谢谢!

1 个答案:

答案 0 :(得分:0)

如果我理解正确的话,当给出一个有库存的盒子时,你想要创建一个新实验,其中包含该盒子中每个库存的样品。

new行动中,请尝试以下操作:

def new
  @experiment = Experiment.new
  if params[:box_id]
    box = Box.find(params[:box_id])
    box.stocks.each do |stock|
      @expirement.samples.build(stock_id: stock.id) 
    end 
  end
end