I have a problem with nested form and has_many relation. Bussiness case: there are laboratories and their suppliers. Suppliers can be shared between labs.
Models
class Lab < ActiveRecord::Base
has_many :lab_suppliers
has_many :suppliers, through: :lab_suppliers
accepts_nested_attributes_for :lab_suppliers
end
class Supplier < ActiveRecord::Base
has_many :lab_suppliers
has_many :labs, through: :lab_suppliers
accepts_nested_attributes_for :lab_suppliers
end
class LabSupplier < ActiveRecord::Base
belongs_to :lab
belongs_to :supplier
accepts_nested_attributes_for :lab
accepts_nested_attributes_for :supplier
end
Form
<%= form_for(@lab) do |f| %>
<div class="field">
<%= f.label :code %><br>
<%= f.text_field :code %>
</div>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class"field">
<%= fields_for :lab_suppliers do |ff| %>
<%= ff.label :supplier_id %><br>
<%= ff.collection_select :supplier_id, Supplier.all, :id, :name, {include_blank: true}, {:multiple => true, :class=>""} %>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Controller
class LabsController < ApplicationController
before_action :set_lab, only: [:show, :edit, :update, :destroy]
# GET /labs/new
def new
@lab = Lab.new
@lab.lab_suppliers.build
end
# POST /labs
# POST /labs.json
def create
#raise params.inspect
@lab = Lab.new(lab_params)
@lab_supplier = @lab.lab_suppliers.new(params[:lab_suppliers])
@lab_supplier.save
@lab.save
private
def lab_params
params.require(:lab).permit(:code, :name, lab_suppliers_attributes: [])
end
end
Result of the inspect on params after submitting form:
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"...",
"lab"=>{"code"=>"L01",
"name"=>"xxx"},
"lab_suppliers"=>{"supplier_id"=>["",
"1",
"3"]},
"commit"=>"Create Lab"}
While submitting form I receive ActiveModel::ForbiddenAttributesError on the line:
@lab_supplier = @lab.lab_suppliers.new(params[:lab_suppliers])
What am i missing to make it work as expected?