0
votes

I've got following Models Associations:

class Receipt < ApplicationRecord
  validates :name, presence: true
  has_many :items, inverse_of: :receipt
  accepts_nested_attributes_for :items
end

class Item < ApplicationRecord
  validates :name, presence: true
  belongs_to :receipt, inverse_of: :items
  belongs_to :variant, inverse_of: :items
end

class Variant < ApplicationRecord
  validates :name, presence: true
  belongs_to :product, inverse_of: :variants
  has_many :items, inverse_of: :variant
end

trying to use simple_form to submit a new receipt containing items which are selections from variants like this:

<%= simple_form_for @receipt do |f| %>
    <div class="form-inputs">
      <%= f.input :name, label: 'Receipt Number', required: :true %>
    </div>
    <div class="form-inputs">
      <%= f.simple_fields_for :items do |builder| %>
      <%= builder.collection_select(:variant, Variant.all, :id, :name, {prompt: 'Choose a Variant'}) %>
      <% end %>
    </div>
    <br />
    <div class="form-actions">
      <%= f.button :submit, 'Save Receipt', class:"btn btn-primary" %>
    </div>
  <% end %>

with controller actions:

def new
    @receipt = Receipt.new
    @receipt.items.build
  end

def create
    @receipt = Receipt.create(receipt_params)
    puts receipt_params
    if @receipt.valid?
      redirect_to receipts_path
    else
      render :new, status: :unprocessable_entity
    end
  end

  private

  def receipt_params
    params.require(:receipt).permit(:name, items_attributes: [:id, :name])
  end

I can select from variants (created in a different form and actions) in the form for a new item but after submitting the neither receipt nor item get stored. The terminal reads unpermitted parameter:

*Processing by ReceiptsController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"tugJchKiHNKwQ53E/LGCJacbrqV86ydLHolRuaB9ngZJ4gQrodOLqrxki2fAwgEfpBkbbAOy2GtfHRjsqjWYyQ==", "receipt"=>{"name"=>"bhbh", "items_attributes"=>{"0"=>{"variant"=>"2"}}}, "commit"=>"Save Receipt"} Unpermitted parameter: variant (0.2ms) BEGIN (0.1ms) ROLLBACK Unpermitted parameter: variant

Rendering receipts/new.html.erb within layouts/application Variant Load (0.4ms) SELECT "variants".* FROM "variants" Rendered receipts/new.html.erb within layouts/application (18.2ms) Completed 422 Unprocessable Entity in 473ms (Views: 465.0ms | ActiveRecord: 0.8ms)*

1

1 Answers

1
votes

try using

<%= builder.collection_select(:variant_id, Variant.all, :id, :name, {prompt: 'Choose a Variant'}) %>

instead of

<%= builder.collection_select(:variant, Variant.all, :id, :name, {prompt: 'Choose a Variant'}) %>

See, I used variant_id instead of variant

Also, permit variant_id

def receipt_params
  params.require(:receipt).permit(:name, items_attributes: [:id, :name, :variant_id])
end