Narf
Narf

Reputation: 33

"ActiveModel::ForbiddenAttributesError " on Rails App ( 5) with nested attributes

I have a simple_form_for that creates an invoice. Through this form, I want the user to be able to create a client that will be associated with that before-mentionned invoice. The current process being to firstly create the client, then associate it to the invoice by selecting it from a collection of created clients when the user create an invoice.

My models :

class Client < ApplicationRecord
  has_many :invoices
end 
class Invoice < ApplicationRecord
  belongs_to :client
  accepts_nested_attributes_for :client, reject_if: :all_blank, allow_destroy: true
end

Invoice controller:

def new
    @invoice = Invoice.new
    @invoice.build_client
end 

def create
    @invoice = Invoice.new(invoice_params)
    @client = @invoice.build_client(params[:invoice][:client_attributes])
    @client.user = current_user
    @client.save
end

And I made sure to update my strong params in Invoice Controller with :

params.require(:invoice).permit(:param1, :param2,client_attributes:[:param1, :param2, :param3, etc..],..)

That being said, when creating an invoice, I ran into an "ActiveModel :: ForbiddenAttributesError", which is set to appears when strong params are not correctly defined. Which, in my case, does not seem to be the case. I found out that adding "params.permit!" in my #Create in the Invoice Controller, allowed me to avoid that error. But that's a trick. It should not be necessary since that's the jobs of the strong params. Has anyone ever came across a similar case, please?

Upvotes: -1

Views: 111

Answers (1)

Narf
Narf

Reputation: 33

Ok, so I figured this thing out. All that was needed to do was to - obviously- save my client before, my invoice. Rather simple, isn't it!

Here is my final Invoice #New #Create

def new
    @invoice = Invoice.new
    @invoice.build_client
end 
def create
  @invoice = Invoice.new(invoice_params)
  @invoice.client.user = current_user
  @invoice.client.save

  if @invoice.save
    redirect_to @invoice
  else
    render :new
  end
end

Upvotes: -1

Related Questions